简体   繁体   English

在什么范围内执行来自JQuery JSONP Ajax请求的回调?

[英]In what scope is the callback from a JQuery JSONP Ajax request being executed?

Say I use this function multiple times and the response is delayed - will I risk the callbacks conflicting? 假设我多次使用此函数,并且响应延迟-我会冒着回调冲突的风险吗? Are callbacks run in global scope? 回调是否在全局范围内运行? I'm hoping to run multiple Ajax calls in parallel. 我希望并行运行多个Ajax调用。

<script>
var getFeature = function (id) {
    $.ajax({
      type: 'GET',
      url: "http://myserver.com/feature.aspx",
      data: {id:id},
      jsonpCallback:"GetFeatureCallback",
      contentType: "application/json",
      dataType: 'jsonp'
    }).done(function (data) {
      //do something with data
    });
}

getFeature(1);
getFeature(2);

</script>

The scope of a callback function is not global.Callback functions will have individual scope as that of a function.The variables declared in the callback functions can't be accessed from outside of the callback function. 回调函数的作用域不是全局的。回调函数将具有与函数相同的作用域。在回调函数中声明的变量不能从回调函数外部访问。

In javascript, scope will be defined at lexical time, so the variables in callback function will be assigned to scope before the ajax query is completed.Values to the variables will only be assigned during execution after the ajax query is completed. 在javascript中,作用域将在词法时间定义,因此回调函数中的变量将在ajax查询完成之前分配给作用域。变量的值将仅在ajax查询完成后的执行期间分配。

When a function is called multiple times same memory location of variables is used each time in javascript, same applies here too.But the execution of the callback function will be synchronous and not parallel.And the order of callback function execution will be the order in which jquery returns.So no collision will occurs. 当一个函数被多次调用时,每次在javascript中都使用相同的变量存储位置,此处同样适用。但是回调函数的执行将是同步的而不是并行的,而回调函数的执行顺序将是哪个jquery返回,所以不会发生冲突。

Yes, the GetFeatureCallback needs to be a global variable for JSONP to work. 是的, GetFeatureCallback需要是一个全局变量, JSONP才能起作用。 If you run getFeature multiple times concurrently, they will collide when using a static name. 如果您同时运行getFeature多次,则使用静态名称时它们将发生冲突。 If you don't pass a value for the jsonpCallback , jQuery will automatically create a new unique name dynamically on every call. 如果您没有传递jsonpCallback的值,则jQuery将在每次调用时自动动态创建一个新的唯一名称。

When the server is badly implemented and does not provide a way of picking the callback name, concurrent requests will all call the same function without any good way to distinguish them. 如果服务器的实现不正确且没有提供选择回调名称的方法,则并发请求将全部调用同一函数,而没有任何好的方法来区分它们。 It might still be feasible to do if the response contains enough information to associate it with the query, but in general you'd better sequence the requests. 如果响应包含足够的信息以将其与查询相关联,那么这样做仍然可能是可行的,但是通常最好对请求进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM