Bildsoe Bildsoe - 1 year ago 139
jQuery Question

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.

var getFeature = function (id) {
type: 'GET',
url: "",
data: {id:id},
contentType: "application/json",
dataType: 'jsonp'
}).done(function (data) {
//do something with data



Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download