ajax数据传输方式实例详解
本文实例讲述了ajax数据传输方式。分享给大家供大家参考,具体如下:
在异步应用程序中发送和接收信息时,常见的可以选择以纯文本和XML作为数据格式(可参考《jQuery学习笔记之Ajax用法实例详解》),现在还有一种比较流行的方式:JSON(JavaScriptObjectNotation)。好了,下面举例说明这三种数据格式在ajax的异步应用。
一、纯文本方式
1、发送/接收数据:
Codeischeap.看代码:
testJs.js
//此函数等价于document.getElementById/document.all
function$(s){if(document.getElementById){returneval('document.getElementById("'+s+'")');}else{returneval('document.all.'+s);}}
//创建XMLHttpRequest对象,以发送ajax请求
functioncreateXMLHTTP(){
varxmlHttp=false;
vararrSignatures=["MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP",
"Microsoft.XMLHTTP"];
for(vari=0;i<arrSignatures.length;i++){
try{
xmlHttp=newActiveXObject(arrSignatures[i]);
returnxmlHttp;
}
catch(oError){
xmlHttp=false;//ignore
}
}
//thrownewError("MSXMLisnotinstalledonyoursystem.");
if(!xmlHttp&&typeofXMLHttpRequest!='undefined'){
xmlHttp=newXMLHttpRequest();
}
returnxmlHttp;
}
varxmlReq=createXMLHTTP();
//发送ajax处理请求(这里简单验证用户名和密码的有效性,默认正确的输入:用户名和密码都是test)
functionvalidatePwd(oTxt){
varurl="/AjaxOperations.aspx";
xmlReq.open("post",url,true);
xmlReq.setRequestHeader("Content-Length",oTxt.value.length+$("txtUserName").value.length);
xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlReq.onreadystatechange=callBack;
xmlReq.send("action=chkPwd&userInfos="+escape(oTxt.value+"/"+$("txtUserName").value));//发送文本
}
functioncallBack(){
if(xmlReq.readyState==4){
if(xmlReq.status==200){
alert(xmlReq.responseText);//接收文本
}
elseif(xmlReq.status==404){
alert("RequestedURLisnotfound.");
}elseif(xmlReq.status==403){
alert("Accessdenied.");
}else
alert("statusis"+xmlReq.status);
}
}
几个附加文件源码:
jsTest.htm
<html> <head> <title>jstest</title> <scriptsrc="js/testJs.js"type="text/javascript"></script> </head> <body> <formid="form1"> <div> 用户名:<inputid="txtUserName"name="txtUserName"type="text"/> 密码:<inputid="txtPwd"name="txtPwd"type="password"onblur="validatePwd(this)"/></div> </form> </body> </html>
AjaxOperations.aspx
<%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="AjaxOperations.aspx.cs"Inherits="WebTest2008.AjaxOperations"%>
AjaxOperations.aspx.cs
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
namespaceWebTest2008
{
publicpartialclassAjaxOperations:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
if(!string.IsNullOrEmpty(Request["action"])&&Request["action"]=="chkPwd")
{
stringresponseTxt="用户名和密码不匹配!";
stringtempStr=Request["userInfos"];
/*测试用实际项目中可以对数据库进行检索等等相关操作,这里简化了*/
if(tempStr.Split(newchar[]{'/'},StringSplitOptions.RemoveEmptyEntries)[0]=="test"&&tempStr.Split(newchar[]{'/'},StringSplitOptions.RemoveEmptyEntries)[1]=="test")
{
responseTxt="验证通过!";
}
Response.Write(responseTxt);
}
}
}
}
一一保存文件,ctrl+F5,运行试试看吧。
上面这种方式是最简单最直接也是最有效的方式。熟练使用最佳。
二、XML方式
1、发送XML数据
testJs.js
//此函数等价于document.getElementById/document.all
function$(s){if(document.getElementById){returneval('document.getElementById("'+s+'")');}else{returneval('document.all.'+s);}}
//创建XMLHttpRequest对象,以发送ajax请求
functioncreateXMLHTTP(){
varxmlHttp=false;
vararrSignatures=["MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP",
"Microsoft.XMLHTTP"];
for(vari=0;i<arrSignatures.length;i++){
try{
xmlHttp=newActiveXObject(arrSignatures[i]);
returnxmlHttp;
}
catch(oError){
xmlHttp=false;//ignore
}
}
//thrownewError("MSXMLisnotinstalledonyoursystem.");
if(!xmlHttp&&typeofXMLHttpRequest!='undefined'){
xmlHttp=newXMLHttpRequest();
}
returnxmlHttp;
}
varxmlReq=createXMLHTTP();
//发送ajax处理请求(这里简单验证用户名和密码的有效性,默认正确的输入:用户名和密码都是test)
functionvalidatePwd(oTxt){
varurl="/AjaxOperations.aspx?action=xmlOp";
varxmlStr="<profile>"+
"<userName>"+escape($("txtUserName").value)+"</userName>"+
"<userPwd>"+escape($("txtPwd").value)+"</userPwd>"+
"</profile>";
xmlReq.open("post",url,true);
//Telltheserveryou'resendingitXML
xmlReq.setRequestHeader("Content-Type","text/xml");//这里注意
xmlReq.onreadystatechange=callBack;
xmlReq.send(xmlStr);//发送XML
}
functioncallBack(){
if(xmlReq.readyState==4){
if(xmlReq.status==200){
alert(xmlReq.responseText);//接收文本
}
elseif(xmlReq.status==404){
alert("RequestedURLisnotfound.");
}elseif(xmlReq.status==403){
alert("Accessdenied.");
}else
alert("statusis"+xmlReq.status);
}
}
jsTest.htm文件不变,AjaxOperations.aspx的HTML文件内容不变,服务器端.CS处理代码如下:
AjaxOperations.aspx.cs
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Xml;
namespaceWebTest2008
{
publicpartialclassAjaxOperations:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
if(!string.IsNullOrEmpty(Request["action"])&&Request["action"]=="xmlOp")//处理xml
{
XmlDocumentdoc=newXmlDocument();
try
{
doc.Load(Request.InputStream);//获取xml数据(这里需要注意接受xml数据的方法)
}
catch(Exceptionex)
{
throwex;
}
stringresponseTxt="";
stringtempName=doc.SelectSingleNode("profile/userName").InnerText;
stringtempPwd=doc.SelectSingleNode("profile/userPwd").InnerText;
if(tempName=="test"&&tempPwd=="test")
{
responseTxt="验证通过!";
}
elseresponseTxt="验证失败!";
Response.Write(responseTxt);//写文本
}
}
}
}
很简单的代码,运行看看吧。
2、接收XML数据:
我们看到,上面两个.js文件里处理返回数据时都用到了xmlReq.responseText的属性,下面我们试试看xmlReq.responseXML属性:
testJs.js
//此函数等价于document.getElementById/document.all
function$(s){if(document.getElementById){returneval('document.getElementById("'+s+'")');}else{returneval('document.all.'+s);}}
//创建XMLHttpRequest对象,以发送ajax请求
functioncreateXMLHTTP(){
varxmlHttp=false;
vararrSignatures=["MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP",
"Microsoft.XMLHTTP"];
for(vari=0;i<arrSignatures.length;i++){
try{
xmlHttp=newActiveXObject(arrSignatures[i]);
returnxmlHttp;
}
catch(oError){
xmlHttp=false;//ignore
}
}
//thrownewError("MSXMLisnotinstalledonyoursystem.");
if(!xmlHttp&&typeofXMLHttpRequest!='undefined'){
xmlHttp=newXMLHttpRequest();
}
returnxmlHttp;
}
varxmlReq=createXMLHTTP();
//发送ajax处理请求(这里简单验证用户名和密码的有效性,默认正确的输入:用户名和密码都是test)
functionvalidatePwd(oTxt){
varurl="/AjaxOperations.aspx?action=xmlOp";
varxmlStr="<profile>"+
"<userName>"+escape($("txtUserName").value)+"</userName>"+
"<userPwd>"+escape($("txtPwd").value)+"</userPwd>"+
"</profile>";
xmlReq.open("post",url,true);
//Telltheserveryou'resendingitXML
xmlReq.setRequestHeader("Content-Type","text/xml");
xmlReq.onreadystatechange=callBack;
xmlReq.send(xmlStr);//发送XML
}
functioncallBack(){
if(xmlReq.readyState==4){
if(xmlReq.status==200){
varxmlDoc=xmlReq.responseXML;//接收XML
//varnodes=xmlDoc.childNodes;
//alert("文件根标签的名称:"+xmlDoc.documentElement.tagName);
//alert("根元素共有子节点个数:"+xmlDoc.documentElement.childNodes.length);
alert(xmlDoc.documentElement.childNodes(0).text);
}
elseif(xmlReq.status==404){
alert("RequestedURLisnotfound.");
}elseif(xmlReq.status==403){
alert("Accessdenied.");
}else
alert("statusis"+xmlReq.status);
}
}
同样,jsTest.htm文件不变,AjaxOperations.aspx的HTML文件内容不变,服务器端.CS处理代码稍作修改如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Xml;
namespaceWebTest2008
{
publicpartialclassAjaxOperations:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
if(!string.IsNullOrEmpty(Request["action"])&&Request["action"]=="xmlOp")//处理xml
{
XmlDocumentdoc=newXmlDocument();
try
{
doc.Load(Request.InputStream);//获取xml数据
}
catch(Exceptionex)
{
throwex;
}
stringresponseXmlTxt="";
stringtempName=doc.SelectSingleNode("profile/userName").InnerText;
stringtempPwd=doc.SelectSingleNode("profile/userPwd").InnerText;
if(tempName=="test"&&tempPwd=="test")
{
responseXmlTxt="<?xmlversion=\"1.0\"encoding=\"utf-8\"?><msg>验证通过!</msg>";//测试用,简单的xml文件
}
elseresponseXmlTxt="<?xmlversion=\"1.0\"encoding=\"utf-8\"?><msg>验证失败!</msg>";
Response.ContentType=("text/xml;charset=UTF-8");//这里必须要设置,否则客户端接收不到这里写好的xml文件
Response.Write(responseXmlTxt);//写xml
Response.End();
}
}
}
}
好了,前面两种方法是大家平时开发中比较熟悉的方式,下面我们来看看第三种方式。
三、JSON方式
json的准备知识:
json是一种简单的数据格式,比xml更轻巧。json是JavaScript的原生格式,这意味着在JavaScript中处理json格式的数据不需要任何特殊的API或工具包。json的语法规则其实很简单:对象是一个无序的“‘名称/值'对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值'对”之间使用“,”(逗号)分隔。看个例子先:
functiontestJson(){
//定义一个user(json的格式,其实就是定义一个js函数(变量)的方式而已)
varuser=
{
"username":"jeffwong",
"age":25,
"info":{"tel":"12345678","cellphone":"13312345678"},
"address"://数组
[
{"city":"beijing","postcode":"101110"},
{"city":"nycity","postcode":"911119"}
]
}
alert(user.username);
alert(user.age);
alert(user.info.cellphone);
alert(user.address[0].city);
alert(user.address[0].postcode);
user.username="xiaowang";
alert(user.username);
}
上面的定义方式看起来很简单,但是如果字段众多,命名方式混杂,出错的概率大大增加,怎么办?这时候你就会想到用程序的方式生成json数据。json提供了json.js包,专门提供了几种常用的json处理函数。下载下来,(json.js点击此处本站下载。),将其引入然后就可以简单的使用object.toJSONString()转换成json数据。看代码:
functionCar(maker,model,year,color){
this.maker=maker;
this.model=model;
this.year=year;
this.color=color;
}
functiontestJson(){
vartempCar=newCar("VW","S",1999,"yellow");
alert(tempCar.toJSONString());
}
也可以使用eval或者parseJSON()方法来转换json数据到object:
functiontestJson(){
varstr='{"name":"jeffwong","age":25,"address":"beijing"}';
vartempObj=eval('('+str+')');
alert(tempObj.toJSONString());//使用eval方法
vartempObj1=str.parseJSON();
alert(tempObj1.toJSONString());//或者使用parseJSON()方法
}
关于json.js的学习,请参考网上其他资源,这里我不再赘述了。说了这么多,实践环节开始了:
ajax利用json发送/接收数据:
//此函数等价于document.getElementById/document.all
function$(s){if(document.getElementById){returneval('document.getElementById("'+s+'")');}else{returneval('document.all.'+s);}}
//创建XMLHttpRequest对象,以发送ajax请求
functioncreateXMLHTTP(){
varxmlHttp=false;
vararrSignatures=["MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP",
"Microsoft.XMLHTTP"];
for(vari=0;i<arrSignatures.length;i++){
try{
xmlHttp=newActiveXObject(arrSignatures[i]);
returnxmlHttp;
}
catch(oError){
xmlHttp=false;//ignore
}
}
//thrownewError("MSXMLisnotinstalledonyoursystem.");
if(!xmlHttp&&typeofXMLHttpRequest!='undefined'){
xmlHttp=newXMLHttpRequest();
}
returnxmlHttp;
}
varxmlReq=createXMLHTTP();
//发送ajax处理请求(这里简单验证用户名和密码的有效性,默认正确的输入:用户名和密码都是test)
functionvalidatePwd(oTxt){
varurl="/AjaxOperations.aspx?action=jsonOp";
//JSON就只是文本,由于不需要特殊编码而且每个服务器端脚本都能处理文本数据,所以可以轻松利用JSON并将其应用到服务器。
varstr='{"userName":"'+$("txtUserName").value+'","userPwd":"'+$("txtPwd").value+'"}';
varjsonStr=str.parseJSON().toJSONString();//you'resendingitJSON
xmlReq.open("post",url,true);
xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlReq.onreadystatechange=callBack;
xmlReq.send("sendStr="+jsonStr);//发送JSON(在服务器上解释JSON)
}
functioncallBack(){
if(xmlReq.readyState==4){
if(xmlReq.status==200){
varjsonStr=xmlReq.responseText.parseJSON().toJSONString();//转化为json数据
alert(jsonStr);
}
elseif(xmlReq.status==404){
alert("RequestedURLisnotfound.");
}elseif(xmlReq.status==403){
alert("Accessdenied.");
}else
alert("statusis"+xmlReq.status);
}
}
附加文件,AjaxOperations.aspx的html页面没有改变,AjaxOperations.aspx.cs代码稍作调整如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
namespaceWebTest2008
{
publicpartialclassAjaxOperations:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
if(!string.IsNullOrEmpty(Request["action"])&&Request["action"]=="jsonOp")//处理JSON
{
stringresponseJsonTxt="";
stringtempStr=Request["sendStr"].Trim(newchar[]{'{','}'});//在服务器上解释JSON需要引用一个能够转化JSON的组件:Json.Net,这里简单测试,略过Json.Net
if(tempStr.Split(newchar[]{','})[0].Split(newchar[]{':'})[1]=="\"test\""&&tempStr.Split(newchar[]{','})[1].Split(newchar[]{':'})[1]=="\"test\"")
{
responseJsonTxt="{\"msg\":\"验证通过!\"}";//测试用
}
elseresponseJsonTxt="{\"msg\":\"验证失败!\"}";
Response.Write(responseJsonTxt);
Response.End();
}
}
jsTest.html引入json.js文件(必须下载json.js文件,否则js报错),如下:
<html> <head> <title>jstest</title> <scriptsrc="js/json.js"type="text/javascript"></script> <scriptsrc="js/testJs.js"type="text/javascript"></script> </head> <body> <formid="form1"> <div> 用户名:<inputid="txtUserName"name="txtUserName"type="text"/> 密码:<inputid="txtPwd"name="txtPwd"type="password"onblur="validatePwd(this)"/></div> </form> </body> </html>
希望本文所述对大家ajax程序设计有所帮助。