jQuery 结合 Json 提交数据到Webservice,并接收从Webservice返回的Json数据

日期
2011/3/31
关键字
, ,

全行业平台的产品发布,仿照淘宝,选择分类时,用到了无刷新选择分类。我采用的做法是:使用目前最流行的JS框架Jquery,使用当下最流行的数据传递格式JSON,服务器端采用Webservice进行数据交互。本文是总结出来的一些心得。希望能对看到本文的读者有所帮助。

简单的Json数据提交有两种方式:get 和 post,区别请参看代码注释。

 

jQuery ajax  webservice:

一、GET 方式
客户端

var data = { classCode: "0001"}; // 这里要直接使用JOSN对象 
$.ajax({ 
    type: "GET", 
    contentType: "application/json; charset=utf-8", 
    url: "/WebServices/ProductPropertyWebService.asmx/GetProductPropertyList", 
    dataType: "json", 
    anysc: false, 
    data: data, 
    success: RenderProperties, 
    error: function (XMLHttpRequest, textStatus, errorThrown) { 
        alert(errorThrown + ':' + textStatus);  // 错误处理 
    } 
}); 



服务器端(C#)

     //UseHttpGet = true 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
     public List<Property> GetProductPropertyList()
     {
        // Get 方式,要在查询字符串里得到参数值
        string classCode = HttpContext.Current.Request["classCode"]; 
        return PropertyManager.GetPropertySet(classCode, "zh-CN").DataList;
     }

       
二、POST 方式          
客户端

// 这里要使用拼接好的JOSN字符串 
var data = '{ classCode: "' + classCode + '", city: "GuangDong" }';    
$.ajax({ 
    type: "POST", 
    contentType: "application/json; charset=utf-8", 
    url: "/WebServices/ProductPropertyWebService.asmx/GetProductPropertyList", 
    dataType: "json", 
    anysc: false, 
    data: data, // Post 方式,data参数不能为空"",如果不传参数,也要写成"{}"
          //否则contentType将不能附加在Request Headers中。 
    success: RenderProperties, 
    error: function (XMLHttpRequest, textStatus, errorThrown) { 
        alert(errorThrown + ':' + textStatus); // 错误处理 
    } 
});

 
服务器端
    // UseHttpGet = false
    [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)] 
    // Post 方式,参数对应JSON字段属性,并自动赋值直接使用
    public List<Property> GetProductPropertyList(string classCode, string city) 
    {
        return PropertyManager.GetPropertySet(classCode, "zh-CN").DataList;
    }

 
 
注意:GET方法与POST方法不同,有参数的时候,如果参数的值不是ASCII字符(比如中文),GET的参数要encodeURI编码,要不服务端接收到的数据为乱码。

 

复杂的Json数据提交

简单的Json 格式的数据如 { name:Yangjun, age:27 }

复杂的Json格式的数据,其实只是Json嵌套,比如: {name:yangjun, age:27, child:[{name:yangke, age:1},{name:yangbin, age:2}]}

如果是这种复杂的Json格式的数据要提交,并在Webservices中获取,然后根据这个Json格式的字符串,序列成.net对象,应该怎么做呢? 
比如我要提交下面的数据:

客户端:

var productPropertyTemplate =  {"ProductId":10024, "PropertyList":[ 
{"PropertyId":18, "PropertyType":"text", "PropertyValue":"号码是100"},  
{"PropertyId":19, "PropertyType":"checkbox", "PropertyValue":"57|28"}]}  

 $.ajax({ 
    type: "GET", 
    contentType: "application/json; charset=utf-8", 
    url: "/WebServices/ProductPropertyWebService.asmx/PostProductPropertyList", 
    anysc: false, 
    data: { propertyList: productPropertyTemplate }, 
    dataType: "json", 
    success: function (result) { alert(result.d) }, 
    error: function (XMLHttpRequest, textStatus, errorThrown) { 
        alert(errorThrown + ':' + textStatus); 
    } 
});


服务器端:

1、要反序列化Json字符为.net对象,有比较多的开源类库,我使用的是.net 3.5版本以上自带的DataContractJsonSerializer,写一个辅助类:
/// <summary> 
/// Json序列化和反序列化的帮助方法 
/// </summary> 
public class JsonHelper 
{ 
    /// <summary> 
    /// JSON序列化:把对象序列化成Json格式的字符串 
    /// </summary> 
    public static string JsonSerializer<T>(T t) 
    { 
        var ser = new DataContractJsonSerializer(typeof(T)); 
        var ms = new MemoryStream(); 
        ser.WriteObject(ms, t); 
        string jsonString = Encoding.UTF8.GetString(ms.ToArray()); 
        ms.Close(); 
        return jsonString; 
    } 
    /// <summary> 
    /// JSON反序列化:根据Json格式的字符串,反序列化成对象 
    /// </summary> 
    public static T JsonDeserialize<T>(string jsonString) 
    { 
        var ser = new DataContractJsonSerializer(typeof(T)); 
        var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); 
        var obj = (T)ser.ReadObject(ms); 
        return obj; 
    } 
} 


2、因为要反序列化成相应的对象,所以先构造两个对象类,注意每个类和类的字段前面的特性修改符:
    [DataContract] 
    public class MProductProperty 
    { 
        [DataMember(Order = 0, IsRequired = true)] 
        public int ProductId { set; get; } 
        [DataMember(Order = 1, IsRequired = true)] 
        public List<MProperty> PropertyList { set; get; } 
    } 
    public class MProperty 
    { 
        [DataMember(Order = 0, IsRequired = true)] 
        public int PropertyId { set; get; } 
        [DataMember(Order = 1, IsRequired = true)] 
        public string PropertyType { set; get; } 
        [DataMember(Order = 2, IsRequired = true)] 
        public string PropertyValue { set; get; } 
    }


3、接收并处理Json数据的Web方法:

[WebMethod] 
[ScriptMethod(UseHttpGet = true)] 
public string PostProductPropertyList() 
{ 
 string jsonString = HttpContext.Current.Request["propertyList"]; 
 // productProperty 成功反序列化成MProductProperty的对象     var productProperty = JsonHelper.JsonDeserialize<MProductProperty>(jsonString); 
 //返回接收成功标识 
 return "postsuccess"; 
}

 
至此,结束,谢谢你坚持看到这里,希望本文对你有所帮助。欢迎在这里提出问题,一起探讨。

2 评论

评论 (2) -

abc
2011/4/1 16:15:01 #
abc People's Republic of China

aaaaaaaaaaaaaa

回复

abc
2011/4/2 15:49:51 #
abc People's Republic of China

不是吧?这样就算是评论了?

回复

添加评论

  Country flag

biuquote
  • 评论
  • 在线预览
Loading