Home > Web Front-end > JS Tutorial > jQuery combines Json to submit data to Webservice and receive Json data returned from Webservice_jquery

jQuery combines Json to submit data to Webservice and receive Json data returned from Webservice_jquery

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 18:10:41
Original
1043 people have browsed it

jQuery ajax webservice: get and post
1. GET method
Client

Copy code The code is as follows:

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", });



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",
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를 사용합니다. 클래스:
코드
코드 복사 코드는 다음과 같습니다.

/// /// 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



코드 복사 코드는 다음과 같습니다. [DataContract]
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 데이터를 받아 처리하는 웹 방식:
코드



코드 복사
코드는 다음과 같습니다: [WebMethod] [ScriptMethod(UseHttpGet = true)]
public string PostProductPropertyList()
{
string jsonString = HttpContext.Current . Request["propertyList"];
var productProperty = JsonHelper.JsonDeserialize(jsonString); // productProperty가 MProductProperty 객체로 성공적으로 역직렬화되었습니다.
//수신 성공 표시 반환
return "postsuccess" ;
}

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Backslash present in Json
From 1970-01-01 08:00:00
0
0
0
mysql storage json error
From 1970-01-01 08:00:00
0
0
0
javascript - Problems with displaying json data
From 1970-01-01 08:00:00
0
0
0
php json conversion
From 1970-01-01 08:00:00
0
0
0
php - How should swagger return json comments?
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template