您好,欢迎访问一九零五行业门户网

几种javascript实现原生ajax的方法

在基于数据的应用中,用户需求的数据如联系人列表,可以从独立于实际网页的服务端取得并且可以被动态地写入网页中,给缓慢的web应用体验着色使之像桌面应用一样。自从js有了各种框架之后,比如jquery,使用ajax已经变的相当简单了。但有时候为了追求简洁,可能项目中不需要加载jquery这种庞大的js插件。但又要使用到ajax这种功能该如何办呢?下面和大家分享几种利用javascript实现原生ajax的方法。
首先实现ajax之前必须要创建一个 xmlhttprequest 对象的。如果不支持创建该对象的浏览器,则需要创建 activexobject,具体方法如下:
var xmlhttp; function createxmlhttprequest(){ if(window.activexobject){ xmlhttp=new activexobject("microsoft.xmlhttp"); }else if(window.xmlhttprequest) xmlhttp=new xmlhttprequest(); }
下面使用上面创建的xmlhttp实现最简单的ajax get请求:
function doget(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'); } } }
使用上面创建的xmlhttp实现最简单的ajax post请求:
function dopost(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'); } } }
下面再分享一个从网上看到的模拟jquery的$.ajax方法的封装:
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){ var type=conf.type;//type参数,可选 var url=conf.url;//url参数,必填 var data=conf.data;//data参数可选,只有在post请求时需要 var datatype=conf.datatype;//datatype参数可选 var success=conf.success;//回调函数可选 if(type==null){//type参数可选,默认为get type="get"; } if(datatype==null){//datatype参数可选,默认为text datatype="text"; } 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+")")); } } } }; }; 该
该方法使用也很简单,和jquery的$.ajax方法一样,不过没那么多的参数。仅仅是简单的实现了一些基本的ajax功能。使用方法如下:
ajax({ type:"post",//post或者get,非必须 url:"test.jsp",//必须的 data:"name=dipoo&info=good",//非必须 datatype:"json",//text/xml/json,非必须 success:function(data){//回调函数,非必须 alert(data.name); } });
以上这几种javascript实现原生ajax的方法你们学会了吗?希望对大家有帮助。
相关推荐:
ajax如何跳转到新的jsp页面的实现方法
jquery使用ajax读取本地json文件的案例
如何解决多个ajax页面请求,页面loading阻塞问题
以上就是几种javascript实现原生ajax的方法的详细内容。
其它类似信息

推荐信息