如何获取 Jquery Ajax Readystates
如何通过 jquery 了解 ajax 请求的就绪状态? 一般来说,如果不使用 jquery,我们将发送这样的 ajax 请求:
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
// do something
}
}
因此,我可以使用上述代码轻松跟踪从 1 到 4 的就绪状态值,并执行必要的操作,例如在就绪状态为 1 时显示加载图标。
但是通过 jquery ajax 调用,我如何跟踪就绪状态值?
我正在通过 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 Ajax Event .
error(jqXHR, textStatus, 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 Ajax Event . 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"
,"error"
,"timeout"
,"abort"
, 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 Ajax Event .
因此,最好的想法是在传递给
beforeSend
的回调中显示指示器,并在
complete
中隐藏它。
示例:
因此,您必须将代码重写为:
$.ajax({
url: 'ajax/test.html',
type: 'POST',
beforeSend: function() {
// show indicator
},
complete: function() {
// hide indicator
},
success: function(data) {
$('.result').html(data);
}
});
尽管我不明白为什么您使用 POST,因为您没有发送任何数据(至少在您的示例代码中)。
http://api.jquery.com/category/ajax/ 我想你会发现这里的不同事件对应着不同的 readyStates。