[英]How do I reference the AJAX request object inside an anonymous function
I use $.ajax()
method from JQuery
to do some POST requests, and inside its error: function(jqXHR, textStatus, errorThrown) { ... }
callback, I want to implement a simple retry mechanism with timeout, eg 我使用
JQuery
$.ajax()
方法执行一些POST请求,并且在其error: function(jqXHR, textStatus, errorThrown) { ... }
内部error: function(jqXHR, textStatus, errorThrown) { ... }
回调,我想实现一个简单的超时重试机制,例如
timeout = window.setTimeout(function() {
$.ajax(myReqOptions);
}, 3000);
myReqOptions
here needs to be the options object I define in $.ajax()
to make this work. myReqOptions
此处必须是我在$.ajax()
定义的选项对象,以使此工作有效。 Is there a convenient way to reference this object other than setting a temp variable before calling the timeout, like this: 除了在调用超时之前设置临时变量之外,是否有一种方便的方法来引用该对象,如下所示:
myReqOptions = this;
timeout = window.setTimeout(function() {
$.ajax(myReqOptions);
}, 3000);
this
here refers to the owner of the error
callback, which is the object I define in $.ajax()
. this
这里指的是所有者error
回调,这是我定义的对象$.ajax()
The temp variable is fine. 临时变量很好。 To shorten the call a littlebit, you can use the
bind
function method : 为了缩短通话时间,您可以使用
bind
函数方法 :
timeout = window.setTimeout($.ajax.bind($, this), 3000);
or, for compatibility with old browser (not using the ES5 shim), with $.proxy
: 或者,为了与旧版浏览器(不使用ES5垫片)兼容,请使用
$.proxy
:
timeout = window.setTimeout($, "ajax", this), 3000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.