ajax原生js面向对象封装及开发时遇到的问题

在工作中我们经常会向后台请求各种数据,遇到各种问题,以自己在该开始开发时经常出现的错误来说明。

1、首先定义一个对象 Ajax

    var Ajax = {
        ajax : function(type,url,callback){
            var xhr = new XMLHttpRequest();//定义对象
            xhr.open(type , url , true);
            if(type == 'post'){
                 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=utf-8');
                xhr.send();
            }else{
                xhr.send();
            }
            xhr.onreadystatechange = function () {
                if( xhr.readyState === 4 && xhr.status ===200){
                    console.log(xhr.responseText)
                    console.log(JSON.parse(xhr.responseText));
                    callback && callback();
                }
            }
        }
}

上面是封装好的Ajax对象,在调用时只需要进行下面操作

window.onload = function (){
    Ajax.ajax('type' ,'自己数据的路径' , function (){//进行数据的处理
        console.log(this);//查看此时的对象是谁
        console.log(arguments);//实参列表
    } )
}

出现下面图片中的问题是如何出现的:
这里写图片描述
(1)没有开启服务器,或者没有再服务器端打开文件,只是本地打开
(2)有可能是服务器端口冲突,没有达到同源策略。

2、在ajax请求时需要给路径后面链接一些参数,然后去请求数据(以post为例封装)

function Post(opt) {
    this.init(opt);
}
Post.prototype = {
    constructor: 'Post',
    init: function (opt) {
        this.method = 'POST';
        this.data = opt.data || null;
        this.url = opt.url || '';
        this.async = true;
        this.success = opt.success || function () {}
        this.format();
    },
    format: function () {//将data中的键值对用变成“键=值&键=值”
        var data = this.data;
        var params = [];
        for (var key in data) {
            params.push(key + '=' + data[key]);
        }
        this.postData = params.join('&');
        this.xhr();
    },
    xhr: function () {
        var that = this;
        var xhr = new XMLHttpRequest();//定义一个对象
        xhr.open(this.method, this.url, this.async);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=utf-8');
        xhr.send(this.postData);//发送
        xhr.onreadystatechange = function () {
            if (xhr.status === 200 && xhr.readyState === 4) {
                that.success(xhr.response);
            }
        }
    }
}

然后调用此函数,demo如下:

new Post({
            url:'http://www.tuling123.com/openapi/api',
            data:{
                "键":"值",
                "键":"值"
            },
            success:function(res){
                console.log(res)
                console.log(this)
                console.log(argunents)
            }
        })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值