how to cancel http request using javascript
i have a page on which there an event handler attached to an onclick
event. when the event fires it passes contents of a textbox to a GET
request. since the url is not in the same domain so i create a script tag and and attach the 开发者_如何学Curl to its source like this
elem.onclick=fire;
function fire()
{
var text=document.getElementById('text').value;
var script=document.createElement("script");
script.className="temp";
script.src="some url"+"?param="+text;
document.body.appendChild(script);
}
now if that event is fired and more than one time i want to cancel all the previous GET
request(because they still might be receiving response) and make the GET
request with latest text. But for this i need to cancel the previous requests.
i tried
document.body.removeChild(script);
script.src=null;
but this does not work in Firefox
(i am using Firefox 5
) although this works in Google Chrome
.Does anyone know if these requests can be cancelled in Firefox and if yes then how?
UPDATE
As suggested by Alfred, i used window.stop
to cancel a request but does not cancel a request but hangs it up. It means that when i look into firebug it looks like the request is being made but there is no response.
The solution is simple: for creating HTTP requests, use <img>
instead of <script>
element. Also you always have to change the src
attribute of the same element.
var img;
function fire()
{
var text = document.getElementById('text').value;
var im = img || (img = new Image());
im.src = "url"+"?param="+text;
}
You may ascertain that it actually works by doing the following: the URL you request should have a huge response time (you can ensure this using e.g. PHP's sleep
function). Then, open Net tab in Firebug. If you click the button multiple times, you'll see that all incomplete requests are aborted.
This is entirely shooting from the hip, but if the script tag has not finished loading you can probably simply script.parentElement.removeChild( script )
. That is more or less what mootools does anyway. (Technically, they replace /\s+/
with ' '
first, but that does not seem to be terribly important).
Would it be ok for you to use a JS framework? If so, MooTools has this functionality built into its Request.JSONP object
I'm not sure if this is what you're looking for, but it seems like a similar issue: http://www.velocityreviews.com/forums/t506018-how-to-cancel-http-request-from-javascript.html
To get around the cross-domain issue, you might be able to use CORS instead (assuming you can change what's on the server): http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
If you do this, you could then use the more standard XMLHttpRequest's abort() function.
CORS is compatible with all the major modern browsers except Opera (http://caniuse.com/cors).
精彩评论