创建一个Ajax

前端之家收集整理的这篇文章主要介绍了创建一个Ajax前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Ajax原生代码

// 对象浅复制
    function extend(dst,obj) {
        for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
                dst[i] = obj[i];
            }
        }
    }

    function json(options) {
        var opt = {
            url: '',type: 'GET',data: {},success: function () {},error: function () {}
        }
        extend(opt,options);
        if (opt.url) {
            var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft XMLHTTP');
            var url = opt.url,type = opt.type,data = opt.data,dataArr = [];
            for (var k in data) {
                dataArr.push(k + "=" + data[k]);
            }
            if (type === "GET") {
                url = url + "?" + dataArr.join("&");
                xhr.open(type,url,true);
                xhr.send();
            }
            if (type === "POST") {
                xhr.open(type,true);
                xhr.setRequestHeader('Content-type','application/x-www-form-rulencoded');
                xhr.send(dataArr.join('&'));
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    var res
                    if (xhr.status === 200 || xhr.status === 304) {
                        if (opt.success && opt.success instanceof Function) {
                            res = xhr.responseText;
                            if (typeof res === 'string') {
                                res = JSON.parse(res);
                            }
                            opt.success.call(xhr,res);
                        }
                    } else {
                        if (opt.error && opt.error instanceof Function) {
                            opt.error.call(xhr,res);
                        }
                    }
                }
            }
        }
    }

测试:

var options = {
        url: 'https://free-api.heweather.com/s6/weather/forecast',data: {
            location: 'beijing',key: '5dafd138ca9841938affbd41798d1cbb'
        },success: function (res) {
            console.log('success');
            console.log(res);
        },error: function (res) {
            console.log('error');
            console.log(res);
        }
    }
    json(options);
原文链接:https://www.f2er.com/ajax/160562.html

猜你在找的Ajax相关文章