面向对象方式封装Ajax
class Ajax{
request(type,url,data,callback){
let xhr = new XMLHttpRequest();
if (type=='post') {//为真,走post
xhr.open('post',url);
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
}else{//否则,走get
xhr.open('get',url);
}
xhr.send(data);
xhr.onreadystatechange = function(){
if (xhr.readyState==4 && xhr.status==200) {
console.log(xhr.response);//符合条件,输出返回结果
//判断是否传递回调函数
callback && callback();
}
}
}
}
调用
ajax.request('post','./oopAjax.php','user=123&pwd=456',function(){
console.log(11111);
});
- 第一个参数是类型,post或get
- 第二个参数是url地址,这里是localhost本地php后台
- 传入的数据,注意是&符号拼接
- 最后加入一个回调函数,程序执行完成需要做的事情可以写入这里
PS:前后端连通之后会再控制台打印输出11111