如何获得Jquery Ajax Readystates

前端之家收集整理的这篇文章主要介绍了如何获得Jquery Ajax Readystates前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我怎么能通过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 the jqXHR (in jQuery 1.4.x,XMLHTTPRequest) object before it is sent. Use this to set custom headers,etc. The jqXHR and settings maps are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5,the beforeSend 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: The data returned from the server,formatted according to the dataType parameter; a string describing the status; and the jqXHR (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: The jqXHR (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 (besides null) are "timeout","error","abort",and "parsererror". This is an 07001. As of jQuery 1.5,the error 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 (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (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,the complete 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,因为你没有发送任何数据(至少在你的示例代码中).

原文链接:https://www.f2er.com/jquery/428436.html

猜你在找的jQuery相关文章