要使用XMLHttpRequest
對象發(fā)送異步請求,請遵循以下步驟:
XMLHttpRequest
對象實例:var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// 請求成功時的操作,例如處理返回的數(shù)據(jù)
console.log(this.responseText);
} else if (this.readyState == 4) {
// 請求失敗時的操作,例如顯示錯誤消息
console.error("Error: " + this.status + " " + this.statusText);
}
};
open()
方法初始化請求。第一個參數(shù)是請求類型(如"GET"或"POST"),第二個參數(shù)是請求的URL,第三個參數(shù)(可選)指定是否異步(通常為true
)。xhttp.open("GET", "your-url-here", true);
application/x-www-form-urlencoded
:xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
send()
方法發(fā)送請求。對于GET請求,參數(shù)為null
;對于POST請求,需要傳遞要發(fā)送的數(shù)據(jù)。xhttp.send(null);
將以上代碼片段組合在一起,完整的示例如下:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
} else if (this.readyState == 4) {
console.error("Error: " + this.status + " " + this.statusText);
}
};
xhttp.open("GET", "your-url-here", true);
xhttp.send(null);
請確保將your-url-here
替換為實際的URL。