Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I cannot stop an ajax request using jQuery and abort() function

My jQuery is below:

var x = $.ajax({
    dataType: "jsonp",
    url: "https://ajax.googleapis.com/ajax/services/search/images?q=google&v=1.0",
    success: function(msg){
       alert( "Jsonp data: " + msg );
    }
});

alert(x);  // x is undefined
// x.abort()​​

You can try this code here: http://jsbin.com/iyile3/2/edit

I want stop this ajax request and stop this ajax request's success function.

But what I get is that "x" is undefined , I think I doesn't stop this ajax request and its success function.

So can anyone help me?

Thank you very much!

like image 763
rqqfccsa Avatar asked Nov 12 '10 06:11

rqqfccsa


People also ask

How do I abort AJAX request?

Just use ajax.abort(); } //then you make another ajax request $. ajax( //your code here );

Can I cancel AJAX request?

We may use the abort() method to cancel a sent AJAX request.

Which function is used to cancel the current request in AJAX?

XMLHttpRequest is an object that we use to send an HTTP request to the server to get the required data from the server. XMLHttpRequest provides an abort() method to cancel the sent request to the server.

How can AJAX execution be stopped after success?

// Perform a simple Ajax request var req = $. ajax({ type: "GET", url: "/user/list/", success: function(data) { // Do something with the data... // Then remove the request. req = null; } }); // Wait for 5 seconds setTimeout(function(){ // If the request is still running, abort it. if ( req ) req.


2 Answers

Well that makes sense.

A jsonp call is not an ordinary XMLHttpRequest (which .ajax() normally returns). It would not work that way since you cannot break out the same origin policy.

JSON-Padding works with dynamic script tag insertion. So basically, jQuery just creates a <script> tag on your site and loads the data over that. No XHR object at all.

I don't think there is a way to early abort that kind of request, but I hope someone will correct me here if I'm wrong.

like image 161
jAndy Avatar answered Sep 20 '22 23:09

jAndy


I think the documentation may be a little misleading on this one. No AJAX request is made when using JSONP. In this case, the ajax function returns an undefined value instead of the object of XMLHTTPRequest.

like image 24
Anurag Avatar answered Sep 20 '22 23:09

Anurag