How to kill old jsonp request?

I have a request for a long polling between domains using getJSON with a callback that looks something like this:

$.getJSON("http://long-polling.com/some.fcgi?jsoncallback=?" function(data){ if(data.items[0].rval == 1) { // update data in page } }); 

The problem is that the request for a long polling service may take some time, and another getJSON request can be made in that time and refresh the page, even if it is an outdated answer.

Req1: h ** p: //long-polling.com/some.fcgi at 10:00 a.m.

req2: h ** p: //long-polling.com/some.fcgi? at 10:01 in the morning

Req1 returns and updates page data 10:02 AM

I need a way to invalidate a return from Req1 if Req2 is already done.

Thanks!

+6
jquery jsonp
source share
4 answers

I don't think this works, since getJSON uses the JSONP method, which actually works by dynamically inserting a script tag that is executed by your browser. I don’t think there is a way to stop the browser from executing a script ...?

+7
source share

When you make an ajax request, it returns an XMLHttpRequest object. If you want abort to call a call, you can call the .abort() method on it.

 var request = $.getJSON(. . . . . ); request.abort(); 
+5
source share

As mentioned in @NewToDB, you cannot cancel the jsonp request (for example, tell the browser that it stops trying to load the src tag), but you can implement a mechanism that effectively ignores the returned data of the old call. Define a global variable that is incremented each time you are about to make a jsonp call and pass the value of this variable to the server as a parameter. You also need to pass the counter back to it from the server (I assume you also have the server code). If the current value of your counter is not equal to the returned value of the counter, then you know that another server call has already been made, so you can ignore the returned data.

 // Global counter var callCounter = 0; 

...

 $.getJSON("http://long-polling.com/some.fcgi?callCounter=" + (++callCounter) + "&jsoncallback=?" function(data){ if(data.items[0].rval == 1 && data.callCounter == callCounter) { // update data in page } }); 
+1
source share

I use a global variable for such a task. This is not a good way, but the easiest.

 if (typeof(myFooRequest) == 'object') { myFooRequest.abort(); myFooRequest = false; } myFooRequest = $.get("/url", function(data) { // ... }); 
0
source share

All Articles