下面是编程之家 jb51.cc 通过网络收集整理的代码片段。
编程之家小编现在分享给大家,也给大家做个参考。
var createAjax = function() { var xhr = null; try { //IE系列浏览器 xhr = new ActiveXObject("microsoft.xmlhttp");
} catch (e1) { try { //非IE浏览器 xhr = new XMLHttpRequest();
} catch (e2) { window.alert("您的浏览器不支持ajax,请更换!");
}
} return xhr;
};
var ajax = function(conf) { // 初始化 //type参数,可选 var type = conf.type; //url参数,必填 var url = conf.url; //data参数可选,只有在post请求时需要 var data = conf.data; //datatype参数可选 var dataType = conf.dataType; //回调函数可选 var success = conf.success; if (type == null){ //type参数可选,默认为get type = "get";
} if (dataType == null){ //dataType参数可选,默认为text dataType = "text";
} // 创建ajax引擎对象 var xhr = createAjax(); // 打开 xhr.open(type,url,true); // 发送 if (type == "GET" || type == "get") {
xhr.send(null);
} else if (type == "POST" || type == "post") {
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send(data);
}
xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { if(dataType == "text"||dataType=="TEXT") { if (success != null){ //普通文本 success(xhr.responseText);
}
}else if(dataType=="xml"||dataType=="XML") { if (success != null){ //接收xml文档 success(xhr.responseXML);
}
}else if(dataType=="json"||dataType=="JSON") { if (success != null){ //将json字符串转换为js对象 success(eval("("+xhr.responseText+")"));
}
}
}
};
};
ajax({ type:"post",url:"test.jsp",data:"name=dipoo&info=good",dataType:"json",success:function(data){ alert(data.name); } });
以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
总结
以上是编程之家为你收集整理的用原生JS对AJAX做简单封装全部内容,希望文章能够帮你解决用原生JS对AJAX做简单封装所遇到的程序开发问题。
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。