Javascript原生ajax请求代码实例
这篇文章主要介绍了Javascript原生ajax请求代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
代码如下
classAjax{
constructor(url,method,data,callback_suc,callback_err,callback_run){
this.RT=true;//默认为异步请求
this.url=url;
this.method=method||"POST";
this.data=data||"";
this.callback_suc=callback_suc||function(){};
this.callback_err=callback_err||function(){};
this.callback_run=callback_run||function(){};
if(!this.url){this.callback_err();return;}
this.createRequest();
}
createRequest(){
letxhr=newXMLHttpRequest();
xhr.onreadystatechange=(e)=>{this.run(e);}
xhr.open(this.method,this.url,this.RT);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(this.data);
}
run(e){
this.callback_run(e);
if(e.target.readyState!==4||e.target.status!==200){return;}
this.callback_suc(e);
}
}
//调用:
newAjax(
"./main.php",//url:请求地址
"POST",//method:请求方法
"data=3&sb=2",//data:传递数据
(e)=>{//callback_suc:请求完成回调函数
document.write(e.target.responseText);//3
},
(e)=>{},//callback_err:请求错误回调函数
(e)=>{}//callback_run:请求中回调函数
)
上面是js代码
下面以main.php为例接收请求
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。