Ajax and readyState

Ajax and readyState

本文关键字:readyState and Ajax      更新时间:2023-09-26

我正在尝试更新我的 ajax 请求函数以显示响应的各个状态。

但是,发送请求后我得到的只是readyState = 1,然后它直接跳转到readyState = 4,我从服务器获得完整的响应。

为什么我没有准备好状态 2 和 3?

当我尝试使用本机浏览器时,例如

xmlhttp2 = new XMLHttpRequest()

发送相同的请求使我在回调中准备好状态 1、2、3 和 4:

xmlhttp2.onreadystatechange

但是使用JQueryajax辅助函数则不然。为什么会这样?

这是我的代码:

var jqXHR = $.ajax(
{
    data: requestForm, //my json request
    type: req_type, // could be post or get
    url: script, // php script
    async: true,
    success: function(response,textStatus, xhr) 
    {
          renderIt(response);
    },
    error: function( xhr, textStatus, errorThrown )
    {
        var errText = "<b>Error "+xhr.status+" : "+xhr.reponseText+" , "+textStatus+", "+errorThrown+" </b>";
        $('#'+div).append(errText);
    }
});
jqXHR.fail(function( data, textStatus, jqXHR ) 
{
   var errText = "<b>Error "+jqXHR.status+" : "+jqXHR.reponseText+" , "+textStatus+", "+" </b>";
   $('#'+div).html(errText);
});
switch(jqXHR.readyState) 
{
case 1:
    $('#'+div).html("'n<center> Connected to Server...<br/> <img src='images/loading.gif' height=30 width=30></center>'n");
    break;
case 2:
    $('#'+div).html("'n<center> Request Recieved...<br/> <img src='images/loading.gif' height=30 width=30></center>'n");
    break;
case 3:
    $('#'+div).html("'n<center>  Receiving Responses.....<br/> <img src='images/loading.gif' height=30 width=30></center>'n");
    $('#'+div).append(xhr.responseText);
    break;
default:
    $('#'+div).html("'n<center>  Awaiting Results.."+jqXHR.readyState+"<br/> <img src='images/loading.gif' height=30 width=30></center>'n");
    break;                                    
 } 

在 jQuery 中你只能得到 1 和 4,因为它的成功回调仅在 ajax 请求完成后触发,并且它不会公开 readystatechange 事件的回调。

因此,如果由于某种原因您需要能够对此事件进行一些处理,则需要直接使用 XMLHttpRequest。