如何使用javascript取消http请求 [英] how to cancel http request using javascript

查看:355
本文介绍了如何使用javascript取消http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,其中附加了一个事件处理程序,附加到 onclick 事件。当事件触发时,将文本框的内容传递给 GET 请求。因为该url不在同一个域,所以我创建一个脚本标签,并将这个url附加到它的源头像这样

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 url 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);
}

现在,如果事件被触发,多次我想取消所有以前的 GET 请求(因为它们仍然可能正在接收响应),并使用最新文本生成 GET 请求。但是为此,我需要取消以前的请求。
我试过

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;

但这不适用于 Firefox (我使用 Firefox 5 )虽然这可以在 Google Chrome 中使用。这些请求可以在Firefox中取消,如果是,那么如何?

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?

更新
如Alfred所建议的,我使用 window.stop 取消请求,但不会取消请求,但将其挂起。这意味着当我看到firebug它看起来像是要求,但没有回应。

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.

推荐答案

解决方案是简单:创建HTTP请求时,使用< img> 而不是< script> 元素。此外,您还必须更改相同元素的 src 属性。

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;
}

您可以通过执行以下操作确定实际工作:您请求的URL应该有一个巨大的响应时间(您可以确保使用例如PHP的 sleep 函数)。然后,在Firebug中打开Net选项卡。如果您多次点击该按钮,您将看到所有不完整的请求都被中止。

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.

这篇关于如何使用javascript取消http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆