<script>
let bt = document.querySelector("input");
let mydiv = document.querySelector("div");
let xhr = "null";
bt.onclick = function () {
xhr = new XMLHttpRequest();
xhr.open("post", "http://localhost:8000/");
// 设置响应体为json
xhr.responseType = "json";
// 设置超时时间
xhr.timeout = 1000;
// 设置超时函数
xhr.ontimeout = function () {
alert("请求超时")
}
xhr.setRequestHeader("content-Type", "hello")
xhr.send("hello=world&name=likun");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status <= 300) {
console.log("success");
// 响应状态码
console.log(xhr.status);
console.log(xhr.readyState);
// 响应头状态描述
console.log(xhr.statusText);
// 响应体
console.log(xhr.response);
console.log(xhr.getAllResponseHeaders());
mydiv.innerHTML = xhr.response.age;
}
}
}
}
// 点击按钮主动取消请求
bt.nextElementSibling.onclick = function () {
xhr.abort();
}
</script>
服务端
let express = require("express");
let app1 = express();
// 接收任何方式的请求
app1.all("/", (r, rs) => {
// 允许跨域
rs.setHeader("Access-Control-Allow-Origin", "*");
// 接收任意头
rs.setHeader("Access-Control-Allow-Headers", "*");
const data = {
name: "nokia",
age: 688
}
setTimeout(() => {
rs.send(JSON.stringify(data));
}, 1000)
})
app1.listen(8000, () => {
console.log(
"8000服务器启动"
);
})
ajax各种属性