简体   繁体   English

如何停止所有ajax请求并接受最新请求?

[英]how can i stop all ajax request and take the latest one?

I have a button like this: 我有一个像这样的按钮:

<input type="button" id="getresult" value="getresult" />

by clicking on this button one ajax call request active. 通过单击此按钮,可以激活一个ajax调用请求。 if i keeps clicking on this button then i get queue of ajax request which are hitting to server and waiting for response. 如果我一直单击该按钮,那么我会收到ajax请求队列,这些请求正在命中服务器并等待响应。 but i want to kill all those request and want to take latest one request. 但我想杀死所有这些请求,并希望接受最新的一个请求。

$('#getresult').click(function() {

var parameters = {data1:'value1',data2:'value2'};

$.post("getresult.php",parameters,function(msg){ 
    console.log(msg);
},'json');

});

I tried the xhr.abort(); 我尝试了xhr.abort(); by assigning the request to this variable. 通过将请求分配给此变量。 but whenever i click the button it abort all the request. 但是每当我单击按钮时,它都会中止所有请求。 i am unable to get the latest request. 我无法获取最新请求。 for an eg. 例如 if I click on the button 6 times then the 6 request will generate then i want to cancel the prev 5 request and want to proceed the 6th one. 如果我单击按钮6次,那么将生成6请求,那么我想取消5前一个请求,并希望继续执行第6个请求。

here is the fiddle: http://jsfiddle.net/s4pbn/308/ 这是小提琴: http : //jsfiddle.net/s4pbn/308/

Disable the button and reable it once request has completed: 禁用按钮,并在请求完成后将其重新启用:

$('#getresult').click(function () {
    this.disabled = true;
    var parameters = {
        data1: 'value1',
        data2: 'value2'
    };

    $.post("getresult.php", parameters, function (msg) {
        console.log(msg);
    }, 'json').always(function () {
        this.disabled = false;
    }.bind(this));
});

EDIT: 编辑:

I cant disable the button. 我无法禁用该按钮。 there is some limitation. 有一些限制。

Really not sure why, but then try: 真的不确定为什么,然后尝试:

$('#getresult').click(function () {
    if (this.pendingRequest) this.pendingRequest.abort();
    var parameters = {
        data1: 'value1',
        data2: 'value2'
    };

    this.pendingRequest = $.post("getresult.php", parameters, function (msg) {
        console.log(msg);
        this.pendingRequest = null;
    }, 'json');
});

But be aware, that's just stopping client browser to listen for previous request response, not server to handle any previous ones. 但是请注意,这只是停止客户端浏览器来侦听先前的请求响应,而不是服务器来处理任何先前的响应。 The first method is better way imho. 第一种方法是更好的恕我直言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM