jQuery备忘之(一):jQuery处理.Net后台返回的Xml格式与Json格式的数据的比较分析

      最近项目空闲下来,手头也没有什么事情,所以研究了一下jQuery对后台返回数据格式的处理。可能也是因为之前用JS写code的习惯,所以比较倾向于用JS处理XML格式的数据,当然这也就会造成我后台返回的数据的格式全部为XML的格式,处理起来相对繁琐。

      当然我也早就发现Jquery与Json格式的数据结合的非常好,但是一直苦于.NET的对数据转换成Json格式的繁琐,所以一直也没有采用Json格式的数据,或者是在数据相对简单的情况下采用Json格式的数据,其他千篇一律XML,但是今天我分析了一下Jquery对两种数据格式的处理之后,完全改变了心态,并力推大家用Jquery + Json处理后台返回数据。

      请看如下比较:

     【Jquery + Xml】

      如下代码是我查询IPInfo表中前10条数据,并以XML格式输出:

代码
public void XmlToAjax()
{
   DataTable dt 
= SQLHelper.ExecuteDataTable(SQLHelper.conStrings, CommandType.Text, "select top(10) * from IPInfo");
   DataSet ds 
= new DataSet();
   ds.Tables.Add(dt);
   
//Console
   Response.ContentType = "text/xml";
   Response.Charset 
= "UTF-8";
   Response.Clear();
   Response.Write(
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n " + ds.GetXml());
   Response.End();
}

 

     我在前台接收到数据后进行如下处理:

代码
function checkText() {
            
var xmlT;
            
if ($.trim($("#txtID").val()) == "") {
                $(
"#sm").text("请输入XML条件");
                $(
"#txtID").focus();
                
return false;
            }
            
else {
                $(
"#sm").text("");
                $.ajax({
                    type: 
"GET",  
                  
//contentType: "application/json", //WebService 会返回Json类型
                    url: "../Ajax/Ajax1.aspx"
                    dataType: 
"xml",
                    data: 
"",  //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到       
                    success: function(result) {     //回调函数,result,返回值
                        var ID = '';
                        $(result).find(
"Table1").each(function() {
                            ID 
+= $(this).children("IPid").text() + "<br>";
                        });
                        $(
"#divMsg").html(ID);
                    }
                });
            }

        }

 

     下面是输出结果:

     result.xml 的结果集为:

 

代码
result.xml
"
<?xml version="1.0"?>
<NewDataSet>
    
<Table1>
        
<IPid>1</IPid>
        
<IPFrom>0.0.0.0        </IPFrom>
        
<IPTo>0.255.255.255  </IPTo>
        
<IPLocation>IANA  CZ88.NET</IPLocation>
        
<IPToNumber>16777215</IPToNumber>
        
<IPFromNumber>0</IPFromNumber>
    
</Table1>
    
<Table1>
        
<IPid>2</IPid>
        
<IPFrom>1.0.0.0        </IPFrom>
        
<IPTo>1.255.255.255  </IPTo>
        
<IPLocation>IANA  CZ88.NET</IPLocation>
        
<IPToNumber>33554431</IPToNumber>
        
<IPFromNumber>16777216</IPFromNumber>
    
</Table1>
    
<Table1>
        
<IPid>3</IPid>
        
<IPFrom>2.0.0.0        </IPFrom>
        
<IPTo>2.255.255.255  </IPTo>
        
<IPLocation>IANA  CZ88.NET</IPLocation>
        
<IPToNumber>50331647</IPToNumber>
        
<IPFromNumber>33554432</IPFromNumber>
    
</Table1>
    
<Table1>
        
<IPid>4</IPid>
        
<IPFrom>3.0.0.0        </IPFrom>
        
<IPTo>3.255.255.255  </IPTo>
        
<IPLocation>美国 新泽西通用电气公司</IPLocation>
        
<IPToNumber>67108863</IPToNumber>
        
<IPFromNumber>50331648</IPFromNumber>
    
</Table1>
    
<Table1>
        
<IPid>5</IPid>
        
<IPFrom>4.0.0.0        </IPFrom>
        
<IPTo>4.9.255.255    </IPTo>
        
<IPLocation>美国  CZ88.NET</IPLocation>
        
<IPToNumber>67764223</IPToNumber>
        
<IPFromNumber>67108864</IPFromNumber>
    
</Table1>
    
<Table1>
        
<IPid>6</IPid>
        
<IPFrom>4.10.0.0       </IPFrom>
        
<IPTo>4.10.255.255   </IPTo>
        
<IPLocation>美国 新泽西州立大学</IPLocation>
        
<IPToNumber>67829759</IPToNumber>
        
<IPFromNumber>67764224</IPFromNumber>
    
</Table1>
    
<Table1>
        
<IPid>7</IPid>
        
<IPFrom>4.11.0.0       </IPFrom>
        
<IPTo>4.11.255.255   </IPTo>
        
<IPLocation>美国 夏威夷</IPLocation>
        
<IPToNumber>67895295</IPToNumber>
        
<IPFromNumber>67829760</IPFromNumber>
    
</Table1>
    
<Table1>
        
<IPid>8</IPid>
        
<IPFrom>4.12.0.0       </IPFrom>
        
<IPTo>4.19.77.255    </IPTo>
        
<IPLocation>美国  CZ88.NET</IPLocation>
        
<IPToNumber>68374015</IPToNumber>
        
<IPFromNumber>67895296</IPFromNumber>
    
</Table1>
    
<Table1>
        
<IPid>9</IPid>
        
<IPFrom>4.19.78.0      </IPFrom>
        
<IPTo>4.19.78.255    </IPTo>
        
<IPLocation>美国 西南政法大学</IPLocation>
        
<IPToNumber>68374271</IPToNumber>
        
<IPFromNumber>68374016</IPFromNumber>
    
</Table1>
    
<Table1>
        
<IPid>10</IPid>
        
<IPFrom>4.19.79.0      </IPFrom>
        
<IPTo>4.19.79.63     </IPTo>
        
<IPLocation>美国 Armed Forces Radio/Television</IPLocation>
        
<IPToNumber>68374335</IPToNumber>
        
<IPFromNumber>68374272</IPFromNumber>
    
</Table1>
</NewDataSet>
"

 

    看到这一串代码,那我接下来面对的问题就是去分析这一串代码,取出我所需要的数据,以前一直都是这样处理的(),就像这一段代码:

    $(result).find("Table1").each(function() {    ID += $(this).children("IPid").text() + "<br>"; });  是要取出XML中的所有IPid的数据。

     (顺便插入一句:因为用Jquery操作XML,所以代码相对比较简洁,如果用JS的话会较之麻烦一些。)

    那我们接下来再看看Jquery是如何处理Json格式的数据的:

   【Jquery + Json】

    在处理之前,首先我们要做一件事,就是将数据库取出的数据转换成Json格式,可能已存在有多种转换方法,这里呢我就先说下自己的Json转换方法:

    首先创建一个JsonHelper的类如下:

代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Runtime.Serialization.Json;

namespace LinqModel
{
    
public static class JsonHelper
    {
        
/// <summary>
        
/// 格式化成Json字符串
        
/// </summary>
        
/// <param name="obj">需要格式化的对象</param>
        
/// <returns>Json字符串</returns>
        public static string ToJson(this object obj)
        {
            
// 首先,当然是JSON序列化
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());

            
// 定义一个stream用来存发序列化之后的内容
            Stream stream = new MemoryStream();
            serializer.WriteObject(stream, obj);

            
// 从头到尾将stream读取成一个字符串形式的数据,并且返回
            stream.Position = 0;
            StreamReader streamReader 
= new StreamReader(stream);
            
return streamReader.ReadToEnd();
        }
    }
}

 

 当然这里我们需要引用两个DLL文件(System.Runtime.Serialization.Json,System.ServiceModel.Web),当然这里直接添加添加.net引用,找到这两个DLL就OK了,然后我们需要创建一个实体类,以便用泛型操作,代码如下:

 

代码
/// <summary>
    
/// 实体类IPInfo 。(属性说明自动提取数据库字段的描述信息)
    
/// </summary>
    [DataContract]
    
public class IPInfo
    {
        
public IPInfo()
        { }
        
#region Model
        
private long _ipid;
        
private string _ipfrom;
        
private string _ipto;
        
private string _iplocation;
        
private string _ipcity;
        
private string _iptonumber;
        
private string _ipfromnumber;
        
/// <summary>
        
/// Key
        
/// </summary>
        [DataMember]
        
public long IPid
        {
            
set { _ipid = value; }
            
get { return _ipid; }
        }
        
/// <summary>
        
/// 区间开始
        
/// </summary>
        [DataMember]
        
public string IPFrom
        {
            
set { _ipfrom = value; }
            
get { return _ipfrom; }
        }
        
/// <summary>
        
/// 区间结束
        
/// </summary>
        [DataMember]
        
public string IPTo
        {
            
set { _ipto = value; }
            
get { return _ipto; }
        }
        
/// <summary>
        
/// 位置
        
/// </summary>
        [DataMember]
        
public string IPLocation
        {
            
set { _iplocation = value; }
            
get { return _iplocation; }
        }
        
/// <summary>
        
/// 城市
        
/// </summary>
        [DataMember]
        
public string IPCity
        {
            
set { _ipcity = value; }
            
get { return _ipcity; }
        }
        
/// <summary>
        
/// 
        
/// </summary>
        [DataMember]
        
public string IPToNumber
        {
            
set { _iptonumber = value; }
            
get { return _iptonumber; }
        }
        
/// <summary>
        
/// 
        
/// </summary>
        [DataMember]
        
public string IPFromNumber
        {
            
set { _ipfromnumber = value; }
            
get { return _ipfromnumber; }
        }
        
#endregion Model

    }

 

 注意:如果要对该类进行序列化,一定要在类前面添加上“[DataContract]”,在属性前面添加上“[DataMember]”,这样才能被“DataContractJsonSerializer”序列化成JSON。

下面我们来看如何调用这个方法转换成Json格式的数据:

代码

public void JsonToAjax() 
        {
            
using (SqlDataReader reader = SQLHelper.ExecuteReader(SQLHelper.conStrings, CommandType.Text, "select top(10) * from IPInfo"))
            {
                List
<LinqModel.IPInfo> list = new List<LinqModel.IPInfo>();
                
while (reader.Read())
                {
                    LinqModel.IPInfo model 
= new LinqModel.IPInfo();
                    model.IPCity 
= reader["IPCity"].ToString();
                    model.IPFrom 
= reader["IPFrom"].ToString();
                    model.IPFromNumber 
= reader["IPFromNumber"].ToString();
                    model.IPid 
= long.Parse(reader["IPid"].ToString());
                    model.IPLocation 
= reader["IPLocation"].ToString();
                    model.IPTo 
= reader["IPTo"].ToString();
                    model.IPToNumber 
= reader["IPToNumber"].ToString();
                    list.Add(model);
                }
                
//list.ToJson();
                Response.Write(list.ToJson());
                Response.End();
            }

        }

 

 

就是如此调用:list.ToJson(),简单吧,下面看一下输出的结果:

 

代码
[{"IPCity":"","IPFrom":"0.0.0.0 ","IPFromNumber":"0","IPLocation":"IANA CZ88.NET","IPTo":"0.255.255.255 ","IPToNumber":"16777215","IPid":1},{"IPCity":"","IPFrom":"1.0.0.0 ","IPFromNumber":"16777216","IPLocation":"IANA CZ88.NET","IPTo":"1.255.255.255 ","IPToNumber":"33554431","IPid":2},{"IPCity":"","IPFrom":"2.0.0.0 ","IPFromNumber":"33554432","IPLocation":"IANA CZ88.NET","IPTo":"2.255.255.255 ","IPToNumber":"50331647","IPid":3},{"IPCity":"","IPFrom":"3.0.0.0 ","IPFromNumber":"50331648","IPLocation":"美国 新泽西通用电气公司","IPTo":"3.255.255.255 ","IPToNumber":"67108863","IPid":4},{"IPCity":"","IPFrom":"4.0.0.0 ","IPFromNumber":"67108864","IPLocation":"美国 CZ88.NET","IPTo":"4.9.255.255 ","IPToNumber":"67764223","IPid":5},{"IPCity":"","IPFrom":"4.10.0.0 ","IPFromNumber":"67764224","IPLocation":"美国 新泽西州立大学","IPTo":"4.10.255.255 ","IPToNumber":"67829759","IPid":6},{"IPCity":"","IPFrom":"4.11.0.0 ","IPFromNumber":"67829760","IPLocation":"美国 夏威夷","IPTo":"4.11.255.255 ","IPToNumber":"67895295","IPid":7},{"IPCity":"","IPFrom":"4.12.0.0 ","IPFromNumber":"67895296","IPLocation":"美国 CZ88.NET","IPTo":"4.19.77.255 ","IPToNumber":"68374015","IPid":8},{"IPCity":"","IPFrom":"4.19.78.0 ","IPFromNumber":"68374016","IPLocation":"美国 西南政法大学","IPTo":"4.19.78.255 ","IPToNumber":"68374271","IPid":9},{"IPCity":"","IPFrom":"4.19.79.0 ","IPFromNumber":"68374272","IPLocation":"美国 Armed Forces Radio\/Television","IPTo":"4.19.79.63 ","IPToNumber":"68374335","IPid":10}]

 

 标准的Json格式,呵呵,看了上面的代码,是不是很方便,我想下面的操作就更简单了,看下面的Jquery代码:

 

代码
 function checkText1() {
            
var xmlT;
            
if ($.trim($("#txtID1").val()) == "") {
                $(
"#sm1").text("请输入Json条件");
                $(
"#txtID1").focus();
                
return false;
            }
            
else {
                $(
"#sm1").text("");
                $.ajax({
                    type: 
"GET"
                    contentType: "application/json",
                    url: "../Ajax/Ajax1.aspx",
                    dataType: "json",
                    data: 
"",  //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到       
                    success: function(result) {     //回调函数,result,返回值
                        var aa = '';
                        aa 
+= result[1]["IPid"+ "<br>";
                        aa 
+= result[1]["IPFrom"+ "<br>";
                        aa 
+= result[1]["IPTo"+ "<br>";
                        aa 
+= result[1]["IPLocation"+ "<br>";
                        aa 
+= result[1]["IPCity"+ "<br>";
                        aa 
+= result[1]["IPToNumber"+ "<br>";
                        aa 
+= result[1]["IPFromNumber"+ "<br>";
                        $(
"#divMsg").html(aa);
                    }
                });
            }

 

我们再来看一下 result的结果集:

result
{...}
    [0]: {...}
    [1]: {...}
    [2]: {...}
    [3]: {...}
    [4]: {...}
    [5]: {...}
    [6]: {...}
    [7]: {...}
    [8]: {...}
    [9]: {...}

result[0]
{...}
    IPCity: ""
    IPFrom: "0.0.0.0        "
    IPFromNumber: "0"
    IPid: 1
    IPLocation: "IANA  CZ88.NET"
    IPTo: "0.255.255.255  "
    IPToNumber: "16777215"

就像操作一个泛型一样简单,便捷。

posted @ 2010-05-20 17:14  弗雷德瑞克杨  阅读(2718)  评论(15编辑  收藏  举报