jquery submits data to webservice with JSON and receives the JSON data returned from WebService _jquery

Source: Internet
Author: User
Tags error handling httpcontext
JQuery Ajax Webservice:get and Post
One, Get way
Client
Copy Code code as follows:

var data = {classcode: "0001"}; To use the Josn object directly here
$.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); Error handling
}
});

Server-side
Code
Copy Code code 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;
}

Second, POST mode
Client
Code
Copy Code code as follows:

var data = ' {classcode: ' + Classcode + ', City: ' Guangdong '} '; Here to use the stitching good 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 can not be empty "", if not pass the parameter, also write "{}", otherwise contenttype will not be attached to the request headers.
Success:renderproperties,
Error:function (XMLHttpRequest, Textstatus, Errorthrown) {
Alert (Errorthrown + ': ' + textstatus); Error handling
}
});

Server-side
Code
Copy Code code as follows:

[Scriptmethod (Responseformat = Responseformat.json, Usehttpget = False)]//Usehttpget = False
Public list<property> getproductpropertylist (string Classcode, String city)//Post method, parameters correspond to JSON field properties, and automatically assign values directly using the
{
Return Propertymanager.getpropertyset (Classcode, "ZH-CN"). DataList;
}

Note: The Get method differs 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 submission
Simple JSON-formatted data such as {Name:yangjun, age:27}
Complex JSON-formatted data, in fact just JSON nesting, such as: {Name:yangjun, age:27, Child:[{name:yangke, Age:1},{name:yangbin, age:2}]}
If this complex JSON-formatted data is to be submitted and fetched in WebServices, and then serialized as a. NET object based on this JSON-formatted string, what should be done?
For example, I would submit the following data:
Client:
Code
Copy Code code as follows:

var productpropertytemplate = {"ProductId": 10024, "propertylist": [
{"PropertyId": "PropertyType": "Text", "PropertyValue": "Number is 100"},
{"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 the JSON character as a. NET object, there are a number of open source libraries, and I'm using a datacontractjsonserializer with the. NET 3.5 version, writing a secondary class:
Code
Copy Code code as follows:

<summary>
How to help JSON serialize and deserialize
</summary>
public class Jsonhelper
{
<summary>
JSON serialization: Serializing an object into a JSON-formatted string
</summary>
public static string jsonserializer<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 deserialization: Deserialized into objects based on JSON-formatted strings
</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 you want to deserialize into the corresponding object, so first construct two object classes, pay attention to each class and the field of the class attribute modifier:
Code
Copy Code code 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;
[DataMember (order = 2, IsRequired = True)]
public string PropertyValue {set;
}

3. Web methods for receiving and processing JSON data:
Code
Copy Code code as follows:

[WebMethod]
[Scriptmethod (Usehttpget = True)]
public string Postproductpropertylist ()
{
String jsonstring = httpcontext.current.request["PropertyList"];
var productproperty = jsonhelper.jsondeserialize<mproductproperty> (jsonstring); Productproperty successfully deserialized to Mproductproperty object
Returns the received success identification
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.