jQuery $.ajax 和 readyStates
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4107909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery $.ajax and readyStates
提问by tetris
How to call the Ajax ready states on the jQuery $.ajax
method?
如何在 jQuery$.ajax
方法上调用 Ajax 就绪状态?
采纳答案by Nick Craver
$.ajax()
returns the XmlHttpRequest object, so if you reallywant to access it as the state changes, you can do this:
$.ajax()
返回 XmlHttpRequest 对象,所以如果你真的想在状态改变时访问它,你可以这样做:
var xhr = $.ajax({ ... });
xhr.onreadystatechange = function() { alert(xhr.readyState); };
But the built-in callbacks should be all you need for most uses, particularly success
and complete
.
但是内置回调应该是大多数用途所需要的,特别是success
和complete
。
To do things before the request fires, use beforeSend
, or more appropriately for most cases, the .ajaxStart()
and .ajaxStop()
events...for example to show a loading message whenever any ajax activity is going on.
要在请求触发之前执行操作,请使用beforeSend
,或者更适合大多数情况下的.ajaxStart()
和.ajaxStop()
事件...例如,在任何 ajax 活动正在进行时显示加载消息。
回答by Jonas Masalskis
Method, tested with jQuery 2.0.2:
方法,用 jQuery 2.0.2 测试:
$.ajax({
beforeSend: function (jqXHR, settings) {
var self = this;
var xhr = settings.xhr;
settings.xhr = function () {
var output = xhr();
output.onreadystatechange = function () {
if (typeof(self.readyStateChanged) == "function") {
self.readyStateChanged(this);
}
};
return output;
};
},
readyStateChanged: function (xhr) {
if (xhr.readyState == 1) {
/* Connected! Do something */
}
},
url: "..."
});
Basically, what I needed was a callback after readyState
becomes 1
(Connected), which, in my case, was useful when implementing long polling "push" notifications with jQuery.
基本上,我需要的是在readyState
变成1
(Connected)之后的回调,就我而言,这在使用 jQuery 实现长轮询“推送”通知时很有用。
回答by treeface
You should be able to get all you need by setting callbacks for the success
, error
, and complete
options in the object you pass into the ajax()
method. Take a look at the documentation:
您应该能够通过对设置回调获取你所需要的success
,error
和complete
你传递到该对象的选择ajax()
方法。看一下文档:
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.ajax/
Basically, it works like this:
基本上,它是这样工作的:
$.ajax({
url: 'ajax/test.html',
success: function(data) {
alert('Load was performed.');
},
error: function() {alert("error occurred.")},
complete: function() {alert("ajax complete.")}
});
You can see the docs for exactly what parameters you have access to in the callback functions.
您可以查看文档,了解您可以在回调函数中访问哪些参数。