XMLHttpRequest打开和发送:如何判断它是否有效 [英] XMLHttpRequest Open and Send: How to tell if it worked

查看:680
本文介绍了XMLHttpRequest打开和发送:如何判断它是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题中所述,我的问题是,是否可以判断XMLhttpRequest中的open和send方法是否真的有效?有指标吗?
示例代码:

As is in the title, my question is, Is is possible to tell if the open and send methods from XMLhttpRequest actually worked? Is there any indicator? example code:

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

我正在尝试对此进行故障处理编码,但我需要能够判断是否请求失败,所以我可以处理它。

I'm trying to code in fault handling to this, but I need to be able to tell if the request failed so I can handle it.

推荐答案

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

This is an an asynchronous operation. Your script continues its execution while the request is being sent.

您使用回调检测状态更改:

You detect the state changes using a callback :

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

这篇关于XMLHttpRequest打开和发送:如何判断它是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆