我有以下代码:
sendRequest : function(data){
var me = this;
this._createData(data);
try{
this.req.open(this.method,this.page,true);
this.req.onreadystatechange=function()
{
if (this.readyState==4 && this.status==200)
{
if(this.responseText)
var response = eval('(' + this.responseText + ')');
else
response = null;
me.callBack(response);
return false;
}
}
this.req.send(this.data);
} catch(err){
me.callBack(response);
}
},
它工作正常,并返回我期望它返回的内容,但是当连接丢失时,它不会进入catch块。我想知道的是当服务器页面不可用时如何捕获请求。
答案 0 :(得分:1)
以下是来自onreadystatechange
的{{3}}的示例:
function reportStatus()
{
if (oReq.readyState == 4 /* complete */) {
if (oReq.status == 200 || oReq.status == 304) {
alert('Transfer complete.');
}
else {
// error occurred
}
}
}
var oReq = new XMLHttpRequest();
oReq.open("GET", "http://localhost/test.xml", true);
oReq.onreadystatechange = reportStatus;
oReq.send();
查看// error occurred
的位置。
此Microsoft's doc page上有一个类似的代码示例。
答案 1 :(得分:0)
我在发送Ajax调用之前设置了一个setTimeout:
var timeout = window.setTimeout("functionToCallOnTimeout()", 2000);
在functionToCallOnTimeout内我停止呼叫:
oReq.current=null;
在肯定回答中我清除了超时:
timeout = null;