XMLHttpRequest.open
XMLHttpRequest.open()
方法用于指定 HTTP 请求的参数,或者说初始化 XMLHttpRequest 实例对象。它一共可以接受五个参数。
void open(
string method,
string url,
optional boolean async,
optional string user,
optional string password
);
method
:表示 HTTP 动词方法,比如GET、POST、PUT、DELETE、HEAD等。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>
还没有评论,来说两句吧...