我有以下 Javascript 代码,它总是向服务器请求一些数据。
;var EVENTS = {};
;(function($) {
EVENTS.Test = {
getEventsData: function() {
var events_request = $.ajax({
url: "test1.php",
contentType: 'application/json-rpc',
type: "GET",
timeout: 30000
});
events_request.done(function(results) {alert(results);});
events_request.fail(function(results) {alert(results);});
events_request.always(this.getEventsData);
}
};
})(jQuery);
EVENTS.Test.getEventsData();
服务器端php如下
<?php
sleep(5);
echo "This is response";
?>
我想要做的是从服务器获取数据,以防“.done 或.fail”完成,所以我使用“.always”函数。但只向服务器发出两次请求,之后就不再发出请求。 我使用Firebug进行调试,但不幸的是没有任何错误。我怎么知道为什么ajax在两次请求后不起作用。如何让它发挥作用?
提前致谢。
最佳答案
问题是当 getEventsData
方法由ajax回调调用 this
不指Test
反对this.getEventsData
将是未定义的。解决方案是使用Function.bind()或$.proxy()将自定义执行上下文传递给回调
events_request.always($.proxy(this.getEventsData, this));
另一个选项是设置 $.ajax() 的上下文选项这样所有的回调都会获得自定义的执行上下文。
This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).
关于javascript - 为什么 jQuery 的 ajax ".always"函数无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25864295/