面试官:写一个Ajax叭。

130 阅读1分钟

Ajax四个状态值,一些函数名就不说了叭,直接上代码。
需要注意的就是发送post请求时,要设置header头。

function myAjax(obj) {
    //get方式传入时,将data内容进行拼接
    function splitStr(data) {
        let arr = [];
        for (let i in data) {
            arr.push(i + '=' + data[i])
        }
        return arr.join('&')
    }
    //1.声明XMLHttpRequest
    //创建对象
    let xhq = new XMLHttpRequest();

    //2.初始化Http请求参数,只初始化并不会发送
    //GET方法
    if (obj.method.toUpperCase() === 'GET') {
        //路径拼接
        xhq.open(obj.method, obj.url + '?' + splitStr(obj.data), typeof obj.async === 'boolean' ? obj.async : true)
        //3.发送此次请求
        xhq.send()
        //post方法
    } else if (obj.method.toUpperCase() === 'POST') {
        xhq.open(obj.method, obj.url, typeof obj.async === 'boolean' ? obj.async : true);
        //以表单提交
        xhq.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        //3.发送此次请求
        xhq.send(obj.data)
    } else {
        xhq.open(obj.method, obj.url, typeof obj.async === 'boolean' ? obj.async : true);
        xhq.send(null)
    }
    //4.监听发送
    xhq.onreadystatechange = function () {
        if (xhq.readyState === 4 && xhq.status === 200) {
            //success回调
            success(xhq.responseText)
        } else {
            error()
        }
    }
}

myAjax({
    url: 'your url',
    method: 'post',
    async: 'true',
    data: {
        username: 'pyx',
        pwd: '123'
    },
    success: function (data) {
        console.log(data);
    },
    error: function (err) {
        console.log(`发生了错误${err}`);
    }
})

记录记录!