我正在尝试更新ajax请求函数,以显示响应的各个状态。
然而,在发送请求之后,我得到的只是readyState = 1,然后直接跳转到readyState = 4,然后从服务器获得完整的响应。
为什么我没有得到readyStates 2和3?
当我尝试使用本机浏览器时,例如
xmlhttp2 = new XMLHttpRequest()发送相同的请求将使我在回调中获得readyStates 1、2、3和4:
xmlhttp2.onreadystatechange但是使用JQuery时,ajax助手函数不会。为什么会发生这种事?
这是我的代码:
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;
} 发布于 2013-10-11 18:16:34
在jQuery中只能得到1和4,因为它的成功回调只在ajax请求完成后才会触发,而it does not expose a callback for the readystatechange event则会触发。
因此,如果由于某种原因需要对此事件进行一些处理,则需要直接使用XMLHttpRequest。
https://stackoverflow.com/questions/19324402
复制相似问题