同样,jsTest.htm文件不变,AjaxOperations.aspx的HTML文件内容不变,服务器端.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数据
}
catch (Exception ex)
{
throw ex;
}
string responseXmlTxt = "";
string tempName = doc.SelectSingleNode("profile/userName").InnerText;
string tempPwd = doc.SelectSingleNode("profile/userPwd").InnerText;
if (tempName == "test" && tempPwd == "test")
{
responseXmlTxt = "<?xml version="1.0" encoding="utf-8" ?> <msg>验证通过!</msg>"; // 测试用,简单的xml文件
}
else responseXmlTxt = "<?xml version="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的语法规则其实很简单:对象是一个无序的“‘名称/值'对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值' 对”之间使用“,”(逗号)分隔。看个例子先:
function testJson() {
//定义一个user(json的格式,其实就是定义一个js函数(变量)的方式而已)
var user =
{
"username": "jeff wong",
"age": 25,
"info": { "tel": "12345678", "cellphone": "13312345678" },
"address": // 数组
[
{ "city": "beijing", "postcode": "101110" },
{ "city": "ny city", "postcode": "911119" }
]
}
alert(user.username);
alert(user.age);
alert(user.info.cellphone);
alert(user.address[0].city);
alert(user.address[0].postcode);
user.username = "xiao wang";
alert(user.username);
}
上面的定义方式看起来很简单,但是如果字段众多,命名方式混杂,出错的概率大大增加,怎么办?这时候你就会想到用程序的方式生成json数据。json提供了json.js包,专门提供了几种常用的json处理函数。下载下来,(json.js点击此处本站下载。) ,将其引入然后就可以简单的使用object.toJSONString()转换成json数据。看代码:









