JQuery submits data to Webservice in combination with Json, and receives Json data returned from Webservice.

Source: Internet
Author: User

JQuery ajax webservice: get and post
1. GET Method
Client
Copy codeThe Code is as follows:
Var data = {classCode: "0001"}; // use the JOSN object directly.
$. 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); // handle the error
}
});

Server
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 obtain the parameter value in the query string
Return PropertyManager. GetPropertySet (classCode, "zh-CN"). DataList;
}

Ii. POST Method
Client
Code
Copy codeThe Code is as follows:
Var data = '{classCode: "' + classCode + '", city: "GuangDong"}'; // The spliced JOSN string must be used here.
$. Ajax ({
Type: "POST ",
ContentType: "application/json; charset = UTF-8 ",
Url: "/WebServices/ProductPropertyWebService. asmx/GetProductPropertyList ",
DataType: "json ",
Anysc: false,
Data: data, // Post method, data parameter cannot be blank "". If no parameter is passed, it must also be written as "{}"; otherwise, contentType cannot be appended to Request Headers.
Success: RenderProperties,
Error: function (XMLHttpRequest, textStatus, errorThrown ){
Alert (errorThrown + ':' + textStatus); // handle the error
}
});

Server
Code
Copy codeThe Code is as follows:
[ScriptMethod (ResponseFormat = ResponseFormat. Json, UseHttpGet = false)] // UseHttpGet = false
Public List <Property> GetProductPropertyList (string classCode, string city) // Post method. The parameter corresponds to the JSON field attribute and is automatically assigned with a value.
{
Return PropertyManager. GetPropertySet (classCode, "zh-CN"). DataList;
}

Note: The GET method is different from the POST method. If the value of a parameter is not an ASCII character (such as Chinese), The GET parameter must be encoded by encodeURI, otherwise, the data received by the server is garbled.
Complex Json data submission
Simple Json format data such as {name: Yangjun, age: 27}
Complex Json data is actually nested in Json format, such as: {name: yangjun, age: 27, child: [{name: yangke, age: 1}, {name: yangbin, age: 2}]}
What should I do if the data in this complicated Json format is to be submitted and obtained in Webservices and then serialized into. net Objects Based on the Json string?
For example, I want to submit the following data:
Client:
Code
Copy codeThe Code is as follows:
Var productPropertyTemplate = {"ProductId": 10024, "PropertyList ":[
{"PropertyId": 18, "PropertyType": "text", "PropertyValue": "The number is 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 );
}
});

Server:
1. To deserialize the Json character as a. net object, there are many open-source class libraries. I use the DataContractJsonSerializer that comes with. net 3.5 or later, and write a helper class:
Code
Copy codeThe Code is as follows:
/// <Summary>
/// Json serialization and deserialization help methods
/// </Summary>
Public class JsonHelper
{
/// <Summary>
/// JSON serialization: serializes an object into a Json string.
/// </Summary>
Public static string JsonSerializer <T> (T t)
{
Var ser = new DataContractJsonSerializer (typeof (T ));
VarMS = new MemoryStream ();
Ser. WriteObject (MS, t );
String jsonString = Encoding. UTF8.GetString (ms. ToArray ());
Ms. Close ();
Return jsonString;
}
/// <Summary>
/// JSON deserialization: deserializes a string in Json format into an object.
/// </Summary>
Public static T JsonDeserialize <T> (string jsonString)
{
Var ser = new DataContractJsonSerializer (typeof (T ));
VarMS = new MemoryStream (Encoding. UTF8.GetBytes (jsonString ));
Var obj = (T) ser. ReadObject (MS );
Return obj;
}
}

2. Because deserialization is required to form the corresponding object, two object classes are constructed first. Note that the attribute modifier before the fields of each class and class is as follows:
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 method for receiving and processing Json data:
Code
Copy codeThe Code is as follows:
[WebMethod]
[ScriptMethod (UseHttpGet = true)]
Public string PostProductPropertyList ()
{
String jsonString = HttpContext. Current. Request ["propertyList"];
Var productProperty = JsonHelper. JsonDeserialize <MProductProperty> (jsonString); // The productProperty is deserialized to the object of MProductProperty.
// Return the successful receipt ID
Return "postsuccess ";
}

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.