XMLHttpRequest.open()
方法用于指定 HTTP 請求的參數,或者說初始化 XMLHttpRequest 執行個體對象。它一共可以接受五個參數。
void open(
string method,
string url,
optional boolean async,
optional string user,
optional string password
);
-
:表示 HTTP 動詞方法,比如GET、POST、PUT、DELETE、HEAD等。method
-
: 表示請求發送目标 URL。url
-
: 布爾值,表示請求是否為異步,預設為true。如果設為false,則send()方法隻有等到收到伺服器傳回了結果,才會進行下一步操作。該參數可選。由于同步 AJAX 請求會造成浏覽器失去響應,許多浏覽器已經禁止在主線程使用,隻允許 Worker 裡面使用。是以,這個參數輕易不應該設為false。async
-
:表示用于認證的使用者名,預設為空字元串。該參數可選。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>