本文介绍: Ajax 如何使用一个完整的 AJAX 请求包括五个步骤:1、创建 XMLHTTPRequest 对象2、使用 open 方法创建 http 请求,并设置请求地址xhr.open(get/posturlasynctrue异步),false同步))经常使用前三个参数3、设置发送数据,用 send 发送请求4、注册事件(给 ajax 设置事件)5、获取响应并更新页面function Api ({url, method = ‘GET’, header = {}, callback

Ajax 如何使用

一个完整的 AJAX 请求包括五个步骤

1、创建 XMLHTTPRequest 对象
2、使用 open 方法创建 http 请求,并设置请求地址
xhr.open(get/posturlasynctrue异步),false同步))
经常使用前三个参数
3、设置发送的数据,用 send 发送请求
4、注册事件(给 ajax 设置事件
5、获取响应并更新页面

function  Api ({url, method = 'GET', header = {}, callback = function(){}}) {
    
    const xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.responseType = 'json';

    for (let x in header) {
        xhr.setRequestHeader(x, header[x]);
    }

    xhr.send();

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            callback(xhr.response);
        }
    }
}
function  Api ({ url, method = 'GET' }) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open(method, url);
        xhr.responseType = 'json';

        // for (let x in header) {
        // xhr.setRequestHeader(x, header[x]);
        // }

        xhr.send();

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                resolve(xhr.response);
                // resolve才有api({}).then()方法
            }
        }
    })
}

原文地址:https://blog.csdn.net/World11_/article/details/124425933

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_15527.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注