jQuery ajax webservice: get and post
1. GET method
Client
var data = { classCode: "0001"}; // The JOSN object is used 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
}
} ; As follows:
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)] //UseHttpGet = true
public List 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;
Code
Copy code
The code is as follows:
var data = '{ classCode: "' classCode '", city: "GuangDong" }'; // The spliced JOSN string should be used here
$.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 empty "", if no parameter is passed, it must also be written as "{}", otherwise the contentType will not be able to Appended in Request Headers. success: RenderProperties, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown ':' textStatus); // Error handling}
});
Server side
Code
Copy code
The code is as follows:
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)] // UseHttpGet = false
public List GetProductPropertyList(string classCode, string city) // Post method, parameters correspond to JSON fields Properties, and automatically assign values directly using
{ return PropertyManager.GetPropertySet(classCode, "zh-CN").DataList;
}
Complex Json format data is actually just Json nesting, such as : {name:yangjun, age:27, child:[{name:yangke, age:1},{name:yangbin, age:2}]}
If this kind of complex Json format data needs to be submitted, And obtain it in Webservices, and then sequence it into a .net object based on this Json format string. What should be done?
For example, I want to submit the following data:
Client:
Code
Copy code
The 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",
alert(errorThrown ':' textStatus);
}
});
서버 측:
1. Json 문자를 .net 객체로 역직렬화하기 위해 .net 버전 3.5 이상과 함께 제공되는 DataContractJsonSerializer를 사용합니다. 클래스:
코드
/// /// Json 직렬화 및 역직렬화를 위한 도우미 메서드
///
공개 클래스 JsonHelper
{
/// ; >/// JSON 직렬화: 객체를 Json 형식 문자열로 직렬화
///
공개 정적 문자열 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;
}
///
/// JSON 역직렬화: Json 형식 문자열에 따라 개체
/ //
public static T JsonDeserialize(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. 해당 개체로 역직렬화해야 하므로 먼저 두 개의 개체 클래스를 구성합니다. 각 클래스 앞의 특성 수정자와 클래스 필드에 주의하세요.
Code
public class MProductProperty
{
[DataMember(Order = 0, IsRequired = true)]
public int ProductId { set; get; }
[DataMember(Order = 1, IsRequired = true)]
public List
}
공용 클래스 MProperty
{
[DataMember(Order = 0, IsRequired = true)]
public int PropertyId { set; , IsRequired = true)]
공용 문자열 PropertyType { 집합; }
[DataMember(Order = 2, IsRequired = true)]
공용 문자열 PropertyValue }
}
3. Json 데이터를 받아 처리하는 웹 방식:
코드
코드 복사
public string PostProductPropertyList()
{
string jsonString = HttpContext.Current . Request["propertyList"];
var productProperty = JsonHelper.JsonDeserialize(jsonString); // productProperty가 MProductProperty 객체로 성공적으로 역직렬화되었습니다.
//수신 성공 표시 반환
return "postsuccess" ;
}