Javascript XMLHttpRequest打开并发送:如何判断它是否有效

Javascript XMLHttpRequest打开并发送:如何判断它是否有效,javascript,xmlhttprequest,Javascript,Xmlhttprequest,正如标题中所述,我的问题是,是否有可能判断XMLhttpRequest中的open和send方法是否实际工作?有什么指标吗? 示例代码: cli = new XMLHttpRequest(); cli.open('GET', 'http://example.org/products'); cli.send(); 我正在尝试编写错误处理代码,但是我需要能够判断请求是否失败,这样我才能处理它 这是一个异步操作。在发送请求时,脚本将继续执行 使用回调检测状态更改: var cli = new XML

正如标题中所述,我的问题是,是否有可能判断XMLhttpRequest中的open和send方法是否实际工作?有什么指标吗? 示例代码:

cli = new XMLHttpRequest();
cli.open('GET', 'http://example.org/products');
cli.send();

我正在尝试编写错误处理代码,但是我需要能够判断请求是否失败,这样我才能处理它

这是一个异步操作。在发送请求时,脚本将继续执行

使用回调检测状态更改:

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

对它是。已经查阅了哪些解释如何使用XHR的在线资源/文档-1.读一些,然后,如果还有不清楚的地方,问一个更直接的问题。(我建议使用XHR包装器,但想法是一样的。)@pst在我看来,操作的异步性质可能很难被新手理解,因此可能会被阻止。这就是我回答的原因。“你认为我不应该这么做吗?”dystroy说,除了这是一个覆盖范围很广的用例。。人们编写文档/教程是有原因的。很抱歉,我只是从中学习,没有意识到就绪状态有数百种,并且是动态更新的。
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
    }
}