參考地址 MDN 中文文檔
// 使用post方式, 發(fā)送請(qǐng)求
let xhr = new XMLHttpRequest();
xhr.timeout = 5000;
xhr.open("POST", url, true);
// setRequestHeader方法必須在 open()方法和 send() 方法之間調(diào)用。
// 如果多次對(duì)同一個(gè)請(qǐng)求頭賦值,只會(huì)生成一個(gè)合并了多個(gè)值的請(qǐng)求頭。
// 若使用的是cocos引擎,在原生平臺(tái)需要設(shè)置此HTTP頭部信息
// xhr.setRequestHeader("Accept-Encoding", "gzip,deflate", "text/html;charset=UTF-8");
xhr.setRequestHeader("Authorization", true);
xhr.onerror = function (res) {
console.log("onerror");
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 &&
(xhr.status >= 200 && xhr.status < 300)) {
console.log("success");
console.log(xhr.responseText);
} else {
console.log("fail");
}
};
// 發(fā)送 obj 若發(fā)送 JSON str 則頭部信息設(shè)為:xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
let data = "nickname=xxxx&sex=xx";
xhr.send(data);