TypechoJoeTheme

至尊技术网

统计
登录
用户名
密码
/
注册
用户名
邮箱

悠悠楠杉

网站页面

原生js封装ajax

2022-09-03
/
0 评论
/
344 阅读
/
正在检测是否收录...
09/03
function ajax(options) {
    var xhr = null;
    var params = formsParams(options.data);
    //创建对象
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest()
    } else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (typeof options.async == 'undefined') {
        options.async = true;
    }
    // 连接
    if (options.type.toLowerCase() == "get") {
        xhr.open(options.type, options.url + "?" + params, options.async);
        xhr.send(null)
    } else if (options.type.toLowerCase() == "post") {
        xhr.open(options.type, options.url, options.async);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(params);
    }
    if (options.async) {
        xhr.onreadystatechange = function () {
            optionsSuccess();
        }
    } else {
        optionsSuccess();
    }

    function optionsSuccess(){
        if (xhr.readyState == 4 && xhr.status == 200) {
                if (typeof options.datatype == 'undefined' || options.datatype == 'json') {
                    options.success(JSON.parse(xhr.responseText));
                } else {
                    options.success(xhr.responseText);
                }
            }
    }

    function formsParams(data) {
        var arr = [];
        for (var prop in data) {
            arr.push(prop + "=" + data[prop]);
        }
        return arr.join("&");
    }
}

// 使用
ajax({
    url: "api.php",// 请求地址
    type: "post",// 请求方式
    async: true,// 同步:false,异步:true,默认为true
    datatype: "json",// 返回数据的格式,"json","text",默认为json
    data: {// post数据
        code: "s2sdd",
        link: location.href
    },
    success: function (res) {// 返回数据
        console.log(res);
    }
})
经验jsajaxjson
朗读
赞(0)
版权属于:

至尊技术网

本文链接:

https://www.zzwws.cn/archives/6358/(转载时请注明本文出处及文章链接)

评论 (0)