简体   繁体   中英

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.

<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.

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.

Yes, the GetFeatureCallback needs to be a global variable for JSONP to work. If you run getFeature multiple times concurrently, they will collide when using a static name. If you don't pass a value for the jsonpCallback , jQuery will automatically create a new unique name dynamically on every call.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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