I\'m using a JSONP ajax call to load some content from a different domain, and all this stuff is executed if the user causes a \"mouseover\" on a button.
I can captu
The basic answer is simply the one given here: You can't really abort()
a JSONP call. So the real question is, how do you avoid both superfluous callback invocations and the error you're seeing?
You can't use try...catch
around the callback because it's asynchronous; you'd have to catch it from jQuery's end, and jQuery generally doesn't handle exceptions thrown from callbacks. (I discuss this in my book, Async JavaScript.) What you want to do instead is use a unique identifier for each Ajax call and, when the success callback is invoked, check whether that identifier is the same as it was when you made the call. Here's an easy implementation:
var requestCount = 0;
$.ajax(url, {
dataType: 'jsonp',
requestCount: ++requestCount,
success: function(response, code) {
if (requestCount !== this.requestCount) return;
// if we're still here, this is the latest request...
}
});
Here I'm taking advantage of the fact that anything you pass to $.ajax
is attached to the object that's used as this
in the callback.
It'd be nice if jQuery made abort()
do this for us, of course.