2017-01-23 122 views
-1

$ .ajax被包装成新的'get'函数。

如果在js文件中只有一个'get'调用,那就好了。 但行中的2个呼叫失败。

更精确, 第一次调用失败,“未捕获的ReferenceError:过程没有定义”, 第二个是成功的,但在成功的功能它有第一“得到”调用数据。

正如我所猜测的那样,'this'/ context有一些问题。你能解释给我吗?

(function() { 
     "use strict"; 

     function get(url, success, error) { 
      $.ajax({ 
       type: "GET", 
       dataType: 'jsonp', 
       jsonp: 'callback', 
       jsonpCallback: 'process', 
       url: url, 
       success: success, 
       error: error 
      }); 
     } 

     get('XXX', 
      function(data, textStatus, jqXHR) { 
       console.log("SUCCESS PING 1"); 
       console.log(data); 
      }, 
      function(jqXHR, textStatus, errorThrown) { 
       console.log("ERROR PIND 1"); 
      }); 

     get('YYY', 
      function(data, textStatus, jqXHR) { 
       console.log("SUCCESS PING 2"); 
       console.log(data); 
      }, 
      function(jqXHR, textStatus, errorThrown) { 
       console.log("ERROR PING 2"); 
      }); 
    })(); 

/* 
=========================================== 
===============console===================== 
=========================================== 
1. ERROR PIND WAR 
2. Uncaught ReferenceError: process is not defined 
    at db?callback=process&_=1485184752755:1 
3. SUCCESS PING DB 
4. Object {data for first call here} 
*/ 
+0

也许你应该通过在不同的JSONP回调。 –

回答

0

首先,这是更好不指定一个定制的回调名称( 'jsonpCallback' 参数)

http://api.jquery.com/jQuery.ajax/

jsonpCallback Type: String or Function() Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function.

的事情是,jQuery的创建在全局函数具有指定名称的窗口对象,然后将其删除。 我没有设法得到jQuery库里面发生的事情的全貌,但是 这个问题肯定是由于它试图调用刚被删除的函数。

删除jsonpCallback PARAM解决问题