加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

创建一个Ajax

发布时间:2020-12-16 03:15:54 所属栏目:百科 来源:网络整理
导读: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 () {

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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读