Ajax基本使用

54 阅读1分钟

POST请求:

//1 创建对象
            const xhr = new XMLHttpRequest();
            //2 初始化,设置请求方法和url ,get请求在后面追加?a=100&b=10
            xhr.open('POST', 'http://127.0.0.1:8000/server');
            // 设置请求头
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.setRequestHeader('name', 'atguigu');
            //3 发送。   post请求在这里
            // xhr.send('a:100&b:200'); 或者xhr.send('a=100&b=200');
            xhr.send('a:100&b:200');
            //4 事件绑定,处理服务端绑定的结果
            //readystate 是xhr对象中的属性,表示状态0 1 2 3 4;
            xhr.onreadystatechange = function () {
                // 判断(服务端返回了所有结果,状态码为4)
                if (xhr.readyState === 4) {
                    // 判断响应状态码 200 404 403 500 2xx表示成功
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // 处理结果,行 头 空行 体
                        // console.log(xhr.status);//状态码
                        // console.log(xhr.statusText);//状态字符串
                        // console.log(xhr.getAllResponseHeaders);//所有响应头 
                        // console.log(xhr.response);//响应体
                        result.innerHTML = xhr.response;

                    }
                }
            }

封装一个AJax函数。

function ajax(options) {
    // 创建XMLHttpRequest对象
    const xhr = new XMLHttpRequest();
    // 初始化参数内容
    // xhr.responseType = 'json';
    options = options || {}
    options.type = (options.type || 'GET').toUpperCase()
    options.dataType = options.dataType || 'json'
    const params = options.data
    // 发送请求
    if (options.type === 'GET') {
        xhr.open('GET', options.url + "?" + getParams(params), true)
        xhr.send(null)
    } else if (options.type === 'POST') {
        xhr.open('POST', options.url, true)
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send(getParams(params))
        console.log(getParams(params))
    }
    // 接受请求
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                options.success(xhr.responseText, xhr.responseXML);
            } else {
                options.fail('参数错误' + this.status)
            }
        }
    }

    // 对数据做处理
    function getParams(data) {
        let arr = []
        for (let key in data) {
            arr.push(`${key}=${data[key]}`)
        }
        return arr.join('&')
    }
}

ajax的使用

ajax({
type:'get',
dataType:'json',
data:{limit:10,},
url:'http://localhost:3000/personalized',
success:function(text,xml){
console.log(json.parse(text))
},
faile:function(status){
console.log(status)
}
})