原生JavaScript实现Ajax的方法
首先为大家分享了原生JavaScript实现Ajax代码,供大家参考,具体内容如下
vargetXmlHttpRequest=function(){
if(window.XMLHttpRequest){
//主流浏览器提供了XMLHttpRequest对象
returnnewXMLHttpRequest();
}elseif(window.ActiveXObject){
//低版本的IE浏览器没有提供XMLHttpRequest对象
//所以必须使用IE浏览器的特定实现ActiveXObject
returnnewActiveXObject("Microsoft.XMLHttpRequest");
}
};
varxhr=getXmlHttpRequest();
xhr.onreadystatechange=function(){
console.log(xhr.readyState);
if(xhr.readyState===3&&xhr.status===200){
//获取成功后执行操作
//数据在xhr.responseText
console.log(xhr.responseText);
}
};
xhr.open("get","data.php",true);
xhr.send("");
下面和大家分享几种利用javascript实现原生ajax的方法。
实现ajax之前必须要创建一个XMLHttpRequest对象。如果不支持创建该对象的浏览器,则需要创建ActiveXObject,具体方法如下:
varxmlHttp;
functioncreatexmlHttpRequest(){
if(window.ActiveXObject){
xmlHttp=newActiveXObject("Microsoft.XMLHTTP");
}elseif(window.XMLHttpRequest){
xmlHttp=newXMLHttpRequest();
}
(1)下面使用上面创建的xmlHttp实现最简单的ajaxget请求:
functiondoGet(url){
//注意在传参数值的时候最好使用encodeURI处理一下,以防出现乱码
createxmlHttpRequest();
xmlHttp.open("GET",url);
xmlHttp.send(null);
xmlHttp.onreadystatechange=function(){
if((xmlHttp.readyState==4)&&(xmlHttp.status==200)){
alert('success');
}else{
alert('fail');
}
}
}
(2)使用上面创建的xmlHttp实现最简单的ajaxpost请求:
functiondoPost(url,data){
//注意在传参数值的时候最好使用encodeURI处理一下,以防出现乱码
createxmlHttpRequest();
xmlHttp.open("POST",url);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send(data);
xmlHttp.onreadystatechange=function(){
if((xmlHttp.readyState==4)&&(xmlHttp.status==200)){
alert('success');
}else{
alert('fail');
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助。