Jeff Wong通过本文主要向大家介绍了ajax数据传输方式实例详解等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
本文实例讲述了ajax数据传输方式。分享给大家供大家参考,具体如下:
在异步应用程序中发送和接收信息时,常见的可以选择以纯文本和XML作为数据格式(可参考《jQuery学习笔记之Ajax用法实例详解》),现在还有一种比较流行的方式:JSON(JavaScript Object Notation)。好了,下面举例说明这三种数据格式在ajax的异步应用。
一、纯文本方式
1、发送/接收数据:
Code is cheap.看代码:
testJs.js
// 此函数等价于document.getElementById /document.all function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } } // 创建 XMLHttpRequest对象,以发送ajax请求 function createXMLHTTP() { var xmlHttp = false; var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]; for (var i = 0; i < arrSignatures.length; i++) { try { xmlHttp = new ActiveXObject(arrSignatures[i]); return xmlHttp; } catch (oError) { xmlHttp = false; //ignore } } // throw new Error("MSXML is not installed on your system."); if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); } return xmlHttp; } var xmlReq = createXMLHTTP(); // 发送ajax处理请求(这里简单验证用户名和密码的有效性,默认正确的输入:用户名和密码都是test) function validatePwd(oTxt) { var url = "/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)); // 发送文本 } function callBack() { if (xmlReq.readyState == 4) { if (xmlReq.status == 200) { alert(xmlReq.responseText); // 接收文本 } else if (xmlReq.status == 404) { alert("Requested URL is not found."); } else if (xmlReq.status == 403) { alert("Access denied."); } else alert("status is " + xmlReq.status); } }</div>
几个附加文件源码:
jsTest.htm
<html> <head> <title>js test</title> <script src="js/testJs.js" type="text/javascript"></script> </head> <body> <form id="form1"> <div> 用户名:<input id="txtUserName" name="txtUserName" type="text" /> 密码:<input id="txtPwd" name="txtPwd" type="password" onblur="validatePwd(this)" /></div> </form> </body> </html></div>
AjaxOperations.aspx
AjaxOperations.aspx.cs
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebTest2008 { public partial class AjaxOperations : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!string.IsNullOrEmpty(Request["action"]) && Request["action"] == "chkPwd") { string responseTxt = "用户名和密码不匹配!"; string tempStr = Request["userInfos"]; /* 测试用 实际项目中可以对数据库进行检索等等相关操作,这里简化了 */ if (tempStr.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries)[0] == "test" && tempStr.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries)[1] == "test") { responseTxt = "验证通过!"; } Response.Write(responseTxt); } } } }</div>
一一保存文件,ctrl+F5,运行试试看吧。
上面这种方式是最简单最直接也是最有效的方式。熟练使用最佳。
二、XML方式
1、发送XML数据
testJs.js
// 此函数等价于document.getElementById /document.all function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } } // 创建 XMLHttpRequest对象,以发送ajax请求 function createXMLHTTP() { var xmlHttp = false; var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]; for (var i = 0; i < arrSignatures.length; i++) { try { xmlHttp = new ActiveXObject(arrSignatures[i]); return xmlHttp; } catch (oError) { xmlHttp = false; //ignore } } // throw new Error("MSXML is not installed on your system."); if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); } return xmlHttp; } var xmlReq = createXMLHTTP(); // 发送ajax处理请求(这里简单验证用户名和密码的有效性,默认正确的输入:用户名和密码都是test) function validatePwd(oTxt) { var url = "/AjaxOperations.aspx?action=xmlOp"; var xmlStr = "<profile>" + " <userName>" + escape($("txtUserName").value) + "</userName>" + " <userPwd>" + escape($("txtPwd").value) + "</userPwd>" + "</profile>"; xmlReq.open("post", url, true); // Tell the server you're sending it XML xmlReq.setRequestHeader("Content-Type", "text/xml"); // 这里注意 xmlReq.onreadystatechange = callBack; xmlReq.send(xmlStr); // 发送XML } function callBack() { if (xmlReq.readyState == 4) { if (xmlReq.status == 200) { alert(xmlReq.responseText); // 接收文本 } else if (xmlReq.status == 404) { alert("Requested URL is not found."); } else if (xmlReq.status == 403) { alert("Access denied."); } else alert("status is " + xmlReq.status); } }</div>
jsTest.htm文件不变,AjaxOperations.aspx的HTML文件内容不变,服务器端.CS处理代码如下:
AjaxOperations.aspx.cs
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml; namespace WebTest2008 { public partial class AjaxOperations : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!string.IsNullOrEmpty(Request["action"]) && Request["action"] == "xmlOp") // 处理xml { XmlDocument doc = new XmlDocument(); try { doc.Load(Request.InputStream); //获取xml数据(这里需要注意接受xml数据的方法) } catch (Exception ex) { throw ex; } string responseTxt = ""; string tempName = doc.SelectSingleNode("profile/userName").InnerText; string tempPwd = doc.SelectSingleNode("profile/userPwd").InnerText; if (tempName == "test" && tempPwd == "test") { responseTxt = "验证通过!"; } else responseTxt = "验证失败!"; Response.Write(responseTxt); // 写文本 } } } }</div>
很简单的代码,运行看看吧。
2、接收XML数据:
我们看到,上面两个.js文件里处理返回数据时都用到了xmlReq.responseText的属性,下面我们试试看xmlReq.responseXML属性:
testJs.js