XMLHttpRequest.open

XMLHttpRequest.open()方法用于指定 HTTP 请求的参数,或者说初始化 XMLHttpRequest 实例对象。它一共可以接受五个参数。

void open(
   string method,
   string url,
   optional boolean async,
   optional string user,
   optional string password
);
  • method:表示 HTTP 动词方法,比如GETPOSTPUTDELETEHEAD等。
  • url: 表示请求发送目标 URL。
  • async: 布尔值,表示请求是否为异步,默认为true。如果设为false,则send()方法只有等到收到服务器返回了结果,才会进行下一步操作。该参数可选。由于同步 AJAX 请求会造成浏览器失去响应,许多浏览器已经禁止在主线程使用,只允许 Worker 里面使用。所以,这个参数轻易不应该设为false。
  • user:表示用于认证的用户名,默认为空字符串。该参数可选。
  • password:表示用于认证的密码,默认为空字符串。该参数可选。

注意,如果对使用过open()方法的 AJAX 请求,再次使用这个方法,等同于调用abort(),即终止请求。

下面发送 POST 请求的例子。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>XMLHttpRequest Open</title>
</head>
<body>
    <script>
        var xhr = new XMLHttpRequest();
        xhr.onloadstart = function (e) {
            console.log('onloadstart');
        };
        xhr.onload = function (e) {
            console.log('onload');
        };
        xhr.onerror = function (e) {
            console.log('error');
        };
        xhr.onabort = function (e) {
            console.log('onabort');
        };
        xhr.onloadend = function (e) {
            console.log('onloadend');
        };
        xhr.onreadystatechange = function (e) {
            console.log(e, xhr.readyState, xhr.status);
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    console.log('success');
                }
            }
        };
        xhr.open("POST", "http://192.168.38.79:8080");
        xhr.send();
        //注意,如果对使用过open()方法的 AJAX 请求,再次使用这个 open() 方法,等同于调用abort(),即终止请求,但onabort事件不会触发。
        xhr.open("POST", "http://192.168.38.79:8080");
    </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值