正如标题中所述,我的问题是,是否可以判断XMLhttpRequest中的open和send方法是否真的有效?有指标吗? 示例代码:
cli = new XMLHttpRequest();
cli.open('GET', 'http://example.org/products');
cli.send();
我正在尝试编写故障处理代码,但我需要能够判断请求是否失败,以便我可以处理它。
答案 0 :(得分:3)
这是一个异步操作。您的脚本会在发送请求时继续执行。
使用回调检测状态更改:
var cli = new XMLHttpRequest();
cli.onreadystatechange = function() {
if (cli.readyState === 4) {
if (cli.status === 200) {
// OK
alert('response:'+cli.responseText);
// here you can use the result (cli.responseText)
} else {
// not OK
alert('failure!');
}
}
};
cli.open('GET', 'http://example.org/products');
cli.send();
// note that you can't use the result just here due to the asynchronous nature of the request
答案 1 :(得分:-1)
req = new XMLHttpRequest;
req.onreadystatechange = dataLoaded;
req.open("GET","newJson2.json",true);
req.send();
function dataLoaded()
{
if(this.readyState==4 && this.status==200)
{
// success
}
else
{
// io error
}
}