原生ajax请求封装

html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>原生ajax封装</title>
</head>
<body>
    <button onclick="get()">get</button>
    <button onclick="post()">post</button>
    <script type="text/javascript">
        function ajax(options = {}) {
            options.type = (options.type || "GET").toUpperCase(); // 请求类型
            options.dataType = options.dataType || "json"; // 返回值类型
            options.async = options.async || true; // 是否异步请求
            var params = "";
            if(options.data) { // 格式化参数
                var arr=[];
                for(var name in options.data){
                    arr.push(encodeURIComponent(name)+"="+encodeURIComponent(options.data[name]));
                }
                arr.push(("v="+Math.random()).replace(".",""));
                params = arr.join("&");
            }
            var xhr; // 创建请求实例
            if(window.XMLHttpRequest) {
                xhr = new XMLHttpRequest();
            }else if(window.ActiveXObject) { // 兼容老版本IE 
                xhr = new ActiveXObject("Microsoft.XMLHTTP")
            }
            // 区分GET||POST
            if(options.type === "GET") {
                xhr.open(options.type, `${options.url}?${params}`, options.async);
                xhr.send(null);
            }else {
                xhr.open(options.type, `${options.url}`, options.async);
                if(options.header) { // 设置请求头
                    for(var key in options.header) {
                        console.log(key, options.header[key])
                        xhr.setRequestHeader(key, options.header[key]);
                    }
                }
                console.log(params)
                xhr.send(params);
            }
          
            xhr.onreadystatechange = function() {
                if(xhr.readyState === 4) {
                    if(xhr.status === 200) {
                        options.success(JSON.parse(xhr.responseText))
                    }else {
                        options.fail(xhr.responseText)
                    }
                    options.complete();
                }
            }
        }
        function get() {
            ajax({
                type: "GET",
                url: "http://localhost:3001/user",
                data: {
                    userId: '123456'
                },
                success(res) {
                console.log(res)
                },
                fail(err) {
                console.log(err)
                },
                complete() {
                console.log(1111)
                }
            })
        }
        function post() {
            ajax({
                type: "POST",
                url: "http://localhost:3001/setUser",
                header: {
                    "Content-type": "application/x-www-form-urlencoded"
                },
                data: {
                    userId: "123456",
                    name: "李四",
                    age: 108
                },
                success(res) {
                    console.log(res)
                },
                fail(err) {
                    console.log(err)
                }
            })
        }
    </script>
</body>
</html>

服务端(方便测试, 简写)

const Koa = require("koa");
const bobyParser = require("koa-bodyparser");
const router = require("koa-router")();
const app = new Koa();
app.use(async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', '*');
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    if (ctx.method == 'OPTIONS') {
        ctx.body = 200; 
    } else {
        await next();
    }
})
router.get("/user", async (ctx) => {
    let data = ctx.request.query;
    if(data.userId === '123456') {
        ctx.body = {
            status: 200,
            message: "请求成功",
            data: {
                name: "张三",
                age: 12
            }
        }
    }else {
        ctx.body = {
            status: 400,
            message: "数据查询失败"
        }
    }
})
router.post("/setUser", async (ctx) => {
    let data = ctx.request.body;
    ctx.body = {
        data
    }
    console.log(data)
})
app.listen("3001", () => {
    console.log("app服务已启动 3001")
})
app.use(bobyParser());
app.use(router.routes());

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值