JavaScript原生xmlHttp与jquery的ajax方法json数据格式实例
javascript版本的ajax发送请求
(1)、创建XMLHttpRequest对象,这个对象就是ajax请求的核心,是ajax请求和响应的信息载体,单是不同浏览器创建方式不同
(2)、请求路径
(3)、使用open方法绑定发送请求
(4)、使用send()方法发送请求
(5)、获取服务器返回的字符串 xmlhttpRequest.responseText;
(6)、获取服务端返回的值,以xml对象的形式存储 xmlhttpRequest.responseXML;
(7)、使用W3CDOM节点树方法和属性对该XML文档对象进行检查和解析。
序言:
近来随着项目的上线实施,稍微有点空闲,闲暇之时偶然发现之前写的关于javascript原生xmlHttpajax方法以及后来jquery插件ajax方法,于是就行了一些总结,因时间原因,并未在所有浏览器上进行测试,目前测试的IE8,9,10,GoogleChrome,MozillaFirefox,Opera常用几款,如大家在进行验证测试发现有问题,请及时反馈与我,谢谢大家。
言归正传,直接上代码:
前端代码
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"> <head> <title>Ajax练习</title> <scriptsrc="/Scripts/jquery-1.4.1.min.js"type="text/javascript"></script> <styletype="text/css"> label{width:50px;display:inline-block;} </style> </head> <body> <divid="contentDiv"> <h2>html5表单元素</h2> <label>E-mail</label><inputtype="email"name="UserEmail"id="UserEmail"value="251608027@qq.com"/><br/> <label>URL:</label><inputtype="url"name="UserURL"id="UserURL"value="http://www.baidu.com"/><br/> <label>Number:</label><inputtype="number"name="UserNumber"id="UserNumber"min="1"max="100"value="87"/><br/> <label>Range:</label><inputtype="range"name="UserRange"min="1"max="100"value="78"/><br/> <label>Date:</label><inputtype="date"name="UserDate"id="UserDate"value="2015-12-01"/><br/> <label>Search:</label><inputtype="search"name="UserSearch"id="UserSearch"value="search"/><br/> <labelid="lblMsg"style="color:Red;width:100%;"></label><br/> <inputtype="button"id="btnXmlHttp"value="提交"onclick="returnxmlPost();"/> <inputtype="button"id="btnAjax"value="Ajax提交"onclick="returnAjax();"/> <inputtype="button"id="btnPost"value="Post提交"onclick="returnPost();"/> <inputtype="button"id="btnGet"value="Get提交"onclick="returnGet();"/> <inputtype="button"id="btnGetJSON"value="GetJSON提交"onclick="returnGetJSON();"/> <inputtype="button"id="btnCustom"value="Custom提交"onclick="returnCustom();"/> <br/><labelid="lblAD"style="color:Red;width:100%;">.NET技术交流群:70895254,欢迎大家</label> <scripttype="text/javascript"> //基础数据 varjsonData={ UserEmail:$("#UserEmail").val(), UserURL:$("#UserURL").val(), UserNumber:$("#UserNumber").val(), UserRange:$("#UserRange").val(), UserDate:$("#UserDate").val(), UserSearch:$("#UserSearch").val() }; //统一返回结果处理 functionData(data,type){ if(data&&data.length>0){ varlblMsg=""; for(i=0;i<data.length;i++){ for(varjindata[i]){ lblMsg+=j+":"+data[i][j]; if(j!="Name"&&j!="UserSearch"){lblMsg+=","} } if(i!=data.length){lblMsg+=";";} } $("#lblMsg").html(type+"请求成功,返回结果:"+lblMsg); } } </script> <scripttype="text/javascript"> //javascript原生ajax方法 functioncreateXMLHttp(){ varXmlHttp; if(window.ActiveXObject){ vararr=["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp","Microsoft.XMLHttp"]; for(vari=0;i<arr.length;i++){ try{ XmlHttp=newActiveXObject(arr[i]); returnXmlHttp; } catch(error){} } } else{ try{ XmlHttp=newXMLHttpRequest(); returnXmlHttp; } catch(otherError){} } } functionxmlPost(){ varxmlHttp=createXMLHttp(); varqueryStr="Ajax_Type=Email&jsonData="+JSON.stringify(jsonData); varurl="/Handler/AjaxHandlerHelper.ashx?no.="+Math.random(); xmlHttp.open('Post',url,true); xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlHttp.send(queryStr); xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4&&xmlHttp.status==200){ vardata=eval(xmlHttp.responseText); Data(data,"javascript原生xmlHttp"); } } } </script> <scripttype="text/javascript"> //jquery$.ajax方法 functionAjax(){ $.ajax({ url:"/Handler/AjaxHandlerHelper.ashx?no.="+Math.random(), type:"Post", async:false, data:{ Ajax_Type:"Email", jsonData:JSON.stringify(jsonData) }, dataType:"json", beforeSend:function(){//发送请求前 $("#btnPost").attr('disabled',"true"); }, complete:function(){//发送请求完成后 $("#btnPost").removeAttr("disabled"); }, error:function(XMLHttpRequest,textStatus,errorThrown){ alert("error!"+errorThrown); //alert("请求错误,请重试!"); }, success:function(data){ Data(data,"Jquery$.ajax"); } }); } //jquery$.post方法 functionPost(){ $.post("/Handler/AjaxHandlerHelper.ashx?no.="+Math.random(), { Ajax_Type:"Email", jsonData:JSON.stringify(jsonData) }, function(data){ Data(data,"Jquery$.post"); } ); } //jquery$.getJSON方法 functionGetJSON(){ $.getJSON("/Handler/AjaxHandlerHelper.ashx?no.="+Math.random(), { Ajax_Type:"Email", jsonData:JSON.stringify(jsonData) }, function(data){ Data(data,"Jquery$.getJSON"); } ); } //jquery$.get方法 functionGet(){ $.get("/Handler/AjaxHandlerHelper.ashx?no.="+Math.random(), { Ajax_Type:"Email", jsonData:JSON.stringify(jsonData) }, function(data){ Data(data,"Jquery$.get"); } ); } </script> <scripttype="text/javascript"> //javascript原生脚本自定义jquery$.ajax方法 varCustomAjax=function(custom){ //初始化 vartype=custom.type;//type参数,可选 varurl=custom.url;//url参数,必填 vardata=custom.data;//data参数可选,只有在post请求时需要 vardataType=custom.dataType;//datatype参数可选 varsuccess=custom.success;//回调函数可选 varbeforeSend=custom.beforeSend;//回调函数可选 varcomplete=custom.complete;//回调函数可选 varerror=custom.error;//回调函数可选 if(type==null){//type参数可选,默认为get type="get"; } if(dataType==null){//dataType参数可选,默认为text dataType="text"; } varxmlHttp=createXMLHttp();//创建ajax引擎对象 xmlHttp.open(type,url,true);//打开 //发送 if(type=="GET"||type=="get"||type=="Get"){//大小写 xmlHttp.send(null); } elseif(type=="POST"||type=="post"||type=="Post"){ xmlHttp.setRequestHeader("content-type","application/x-www-form-urlencoded"); xmlHttp.send(data); } xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4&&xmlHttp.status==200){ if(dataType=="text"||dataType=="TEXT"){ if(success!=null){ //普通文本 success(xmlHttp.responseText); } }elseif(dataType=="xml"||dataType=="XML"){ if(success!=null){ //接收xml文档 success(xmlHttp.responseXML); } }elseif(dataType=="json"||dataType=="JSON"){ if(success!=null){ //将json字符串转换为js对象 success(eval("("+xmlHttp.responseText+")")); } } } }; }; //自定义方法 functionCustom(){ CustomAjax({ type:"Post", url:"/Handler/AjaxHandlerHelper.ashx?no.="+Math.random(), data:"Ajax_Type=Email&jsonData="+JSON.stringify(jsonData), dataType:"json", success:function(data){ Data(data,"Custom自定义"); } }); } </script> </div> </body> </html>
.ashx后端代码
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Web; usingSystem.Web.Script.Serialization; usingSystem.Runtime.Serialization.Json; usingSystem.IO; usingSystem.Text; namespaceWebHTML5.Handler { ///<summary> ///AjaxHandlerHelper的摘要说明 ///</summary> publicclassAjaxHandlerHelper:IHttpHandler { publicvoidProcessRequest(HttpContextcontext) { context.Response.ContentType="application/json"; //context.Response.Charset="utf-8"; varAjax_Type=context.Request.QueryString["Ajax_Type"]==null? context.Request.Form["Ajax_Type"]:context.Request.QueryString["Ajax_Type"]; switch(Ajax_Type) { case"Email": context.Response.Write(PostEmail(context)); break; default: context.Response.Write("[{\"Age\":28,\"Name\":\"张鹏飞\"}]"); break; } } publicstaticstringPostEmail(HttpContextcontext) { stringsemail=string.Empty; if(context.Request.HttpMethod=="GET") { semail="["+context.Request.QueryString["jsonData"]+"]"; } else { semail="["+context.Request.Form["jsonData"]+"]"; } returnsemail; } ///<summary> ///JSON序列化 ///</summary> publicstaticstringJsonSerializer<T>(Tt) { DataContractJsonSerializerser=newDataContractJsonSerializer(typeof(T)); MemoryStreamms=newMemoryStream(); ser.WriteObject(ms,t); stringjsonString=Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); returnjsonString; } ///<summary> ///JSON反序列化 ///</summary> publicstaticTJsonDeserialize<T>(stringjsonString) { DataContractJsonSerializerser=newDataContractJsonSerializer(typeof(T)); MemoryStreamms=newMemoryStream(Encoding.UTF8.GetBytes(jsonString)); Tobj=(T)ser.ReadObject(ms); returnobj; } publicboolIsReusable { get { returnfalse; } } } }
Jquery方法扩展
关于Jquery的方法扩展大家自行google或百度;
结束语
说明一下情况:案例中出现的html5range标签的取值问题,写的不对,大家不要在意这些,关于range标签如何取值大家自行google或百度;