微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ajax各种属性


<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服务器启动"
    );
})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐