jquery submits JSON data to webservice and receives the returned JSON data

Source: Internet
Author: User

JQuery Ajax Webservice:get and Post

One, GET mode client

Copy CodeThe code is as follows: var data = {classcode: "0001"}; Here to directly use the Josn object $.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 (ErrorThro WN + ': ' + textstatus); Error handling}});

server-side code

Copy CodeThe code is as follows: [Scriptmethod (Responseformat = Responseformat.json, Usehttpget = true)]//usehttpget = True public list<property > Getproductpropertylist () {String classcode = httpcontext.current.request["Classcode"];//Get method to get the parameter value in the query string Return Propertymanager.getpropertyset (Classcode, "ZH-CN"). DataList; }

Second, POST mode client code

Copy CodeThe code is as follows: var data = ' {classcode: ' + Classcode + ' ", City:" Guangdong "} '; Here to use the spliced Josn string $.ajax ({type: "POST", ContentType: "Application/json; Charset=utf-8 ", url:"/webservices/productpropertywebservice.asmx/getproductpropertylist ", DataType:" JSON ", ANYSC: False, Data:data,//Post mode, the data parameter cannot be null "", if not passed parameter, also write "{}", otherwise contenttype will not be attached in request headers. Success:renderproperties, Error:function (XMLHttpRequest, Textstatus, Errorthrown) {alert (Errorthrown + ': ' + TextStatu s); Error handling}});

server-side code

Copy CodeThe code is as follows: [Scriptmethod (Responseformat = Responseformat.json, Usehttpget = False)]//Usehttpget = False Public List<proper Ty> getproductpropertylist (String Classcode, String city)//Post, parameters corresponding to JSON field properties, and automatically assigned values directly using {return Propertymanager.getpropertyset (Classcode, "ZH-CN"). DataList; }

Note: The Get method is different from the post method, when there are parameters, if the value of the parameter is not an ASCII character (such as Chinese), the get parameter is encodeURI encoded, or the data received by the server is garbled. complex JSON data submits simple JSON-formatted data such as {Name:yangjun, age:27} complex JSON-formatted data, in fact just json nesting, for example: {Name:yangjun, age:27, child:[{ Name:yangke, Age:1},{name:yangbin, age:2}]} If this is a complex JSON-formatted data to be submitted and obtained in WebServices, then based on this JSON-formatted string, Sequence into a. NET object, what should you do? For example, I want to submit the following data: client: code

Copy CodeThe code is as follows: var productpropertytemplate = {"ProductId": 10024, "propertylist": [{"PropertyId": "PropertyType": "Text", " PropertyValue ":" Number is "}, {" PropertyId ": +," 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);} });

Server side: 1, to deserialize JSON characters into. NET objects, there are more open source class libraries, I am using the. NET 3.5 version of the DataContractJsonSerializer, write an auxiliary class: code

Copy CodeThe code is as follows://<summary>///JSON serialization and deserialization help method///</summary> public class Jsonhelper {///<summary>//JSON Serialization: Serializing an object into a JSON-formatted string///</summary> public static string jsonserializer<t> (T t) {var ser = new DATACONTRACTJ Sonserializer (typeof (T)); var ms = new MemoryStream (); Ser. WriteObject (MS, T); String jsonstring = Encoding.UTF8.GetString (ms. ToArray ()); Ms. Close (); return jsonstring; }///<summary>///JSON deserialization: Deserialized into an object based on a JSON-formatted string,///</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, because to deserialize to the corresponding object, so first constructs two object class, notice each class and the class's field preceding the attribute modifier: code

Copy CodeThe code is as follows: [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. Web methods for receiving and processing JSON data: code

Copy CodeThe code is as follows: [WebMethod] [Scriptmethod (Usehttpget = True)] public string postproductpropertylist () {String jsonstring = Httpcont Ext. current.request["PropertyList"]; var productproperty = jsonhelper.jsondeserialize<mproductproperty> (jsonstring); Productproperty successfully deserialized into Mproductproperty object//Return to receive successful identity return "postsuccess"; }

jquery submits JSON data to webservice and receives the returned JSON data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.