简体   繁体   English

在请求期间修改jQuery $ .ajax()成功方法

[英]Modifying jQuery $.ajax() success method during request

In the web app I am working on there is potential for very long running ajax queries. 在Web应用程序中,我正在研究长期运行的Ajax查询的可能性。

I'm using jQuery's $.ajax method to do something like: 我正在使用jQuery的$ .ajax方法来做类似的事情:

this._xhr = jQuery.ajax({
    type: "GET",
    url: "/path/to/service",
    data: "name=value",
    success: function(data, message){
        // handle a success
    },
    dataType: "json"
});

Is there a way to modify the success callback after this._xhr.readyState = 2 (loaded) and before this._xhr.readyState = 4 (completed) 在this._xhr.readyState = 2(已加载)之后,在this._xhr.readyState = 4(已完成)之前,是否可以修改成功回调

I tried modifying this._xhr.onreadystatechange but found that jQuery does not define onreadystatechange. 我尝试修改this._xhr.onreadystatechange,但是发现jQuery没有定义onreadystatechange。

The abort method sounds like the best option to me. abort方法听起来对我来说是最好的选择。

I don't know much about the ajax method internals, but I can think of a few ways to do what you want. 我对ajax方法的内部知识了解不多,但是我可以想到一些执行所需操作的方法。 Both involve global state and would break if it's possible for your user to send a second request before the first has finished, so I'm not sure I recommend them. 两者都涉及全局状态,如果您的用户有可能在第一个请求完成之前发送第二个请求,则它们都会中断,因此我不确定我是否建议他们。

First, you could keep a reference to the method that does your success work, and change it: 首先,您可以保留对成功工作方法的引用,并对其进行更改:

MySuccessMethod = function(d, m) { /* handle a success */ };

this._xhr = jQuery.ajax({
    type: "GET",
    url: "/path/to/service",
    data: "name=value",
    success: function(data, message){ MySuccessMethod(data, message); },
    dataType: "json"
});


// later...
// user cancels request, so change the success method
MySuccessMethod = function(d, m) { /*print a simple message*/ }

Alternatively, you could just put all the logic in the one success method, and use a global flag to determine what to do: 或者,您可以将所有逻辑放在一个成功方法中,并使用全局标志来确定要执行的操作:

success: function(data, message){
    if (RequestHasBeenCancelled) {
        //display a simple message
    }
    else {
        // handle a success
    }
},

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

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