我怎么能通过jquery知道ajax请求的readystates?
通常,不使用jquery,我们将发送一个这样的ajax请求:
http.open("POST",url,true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
// do something
}
}
因此,我可以使用上面的代码轻松跟踪1到4的readystate值,并执行必要的操作,例如当readystate为1时显示加载图标.
但是通过jquery ajax调用,我如何跟踪readystate值?
我正在通过jquery进行ajax调用,如下所示:
$.post('ajax/test.html',function(data) {
$('.result').html(data);
});
$.ajax
的文档.你有可能传递不同的回调(也许不是为了外翻“就绪状态”,但它对指标来说已经足够了):
beforeSend(jqXHR,settings)
Function
A pre-request callback function that can be used to modify thejqXHR
(in jQuery 1.4.x,XMLHTTPRequest
) object before it is sent. Use this to set custom headers,etc. ThejqXHR
andsettings
maps are passed as arguments. This is an Ajax Event. Returningfalse
in thebeforeSend
function will cancel the request. As of jQuery 1.5,thebeforeSend
option will be called regardless of the type of request.
success(data,textStatus,jqXHR)
Function,Array
A function to be called if the request succeeds. The function gets passed three arguments: Thedata
returned from the server,formatted according to thedataType
parameter; a string describing the status; and thejqXHR
(in jQuery 1.4.x,XMLHttpRequest
) object. As of jQuery 1.5,the success setting can accept an array of functions. Each function will be called in turn. This is an 07001.
error(jqXHR,errorThrown)
Function
A function to be called if the request fails. The function receives three arguments: ThejqXHR
(in jQuery 1.4.x,XMLHttpRequest
) object,a string describing the type of error that occurred and an optional exception object,if one occurred. Possible values for the second argument (besidesnull
) are"timeout"
,"error"
,"abort"
,and"parsererror"
. This is an 07001. As of jQuery 1.5,theerror
setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.
complete(jqXHR,textStatus)
Function,Array
A function to be called when the request finishes (aftersuccess
anderror
callbacks are executed). The function gets passed two arguments: ThejqXHR
(in jQuery 1.4.x,XMLHTTPRequest
) object and a string categorizing the status of the request ("success"
,"notmodified"
,"timeout"
,or"parsererror"
). As of jQuery 1.5,thecomplete
setting can accept an array of functions. Each function will be called in turn. This is an 07001.
所以最好的想法是在传递给beforeSend的回调中显示指标并将其隐藏完整.
例:
因此,您必须将代码重写为:
$.ajax({
url: 'ajax/test.html',type: 'POST',beforeSend: function() {
// show indicator
},complete: function() {
// hide indicator
},success: function(data) {
$('.result').html(data);
}
});
虽然我不明白为什么你使用POST,因为你没有发送任何数据(至少在你的示例代码中).