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