Search code examples
jqueryajaxcallbackjsonpabort

Abort JSONP ajax request with jQuery


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 capture the $.ajax() call return as a xhr object, and use it to abort the ajax request each time the user causes a "mouseover". But the JSONP callback function still gets called, and this causes an error, and I think it is beacuse the xhr.abort() method does not prevent the callback function to be called.

I've tried surrounding the $.ajax() call with try{}catch(e){}, but after I call the xhr.abort() method, the error continues.

Is there a way to handle that exception?

The raised exception is like this (according to Firebug): jQuery16102234208755205157_1308941669256 is not a function

And the exception's internal structure is like this: jQuery16102234208755205157_1308941669256({... my json data from a different domain....})


Solution

  • In jQuery 1.5 all the Ajax APIs have a wrapper object around the native XHR objects. Take a look at:

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

     jqxhr.abort(); // should be what you're looking for