JQuery calls WebService and returns JSON data and parameter settings.

Source: Internet
Author: User

. The release of NET Framework 3.5 solves the json problem in WebService calling. This article introduces jQuery calling based on. NET Framework 3.5 WebService returns JSON data. In addition, it also introduces problems caused by improper parameter settings and settings for WebService calling using jQuery, as well as the causes of problems.

JQuery has many web-based WebService calls. Recently, many projects have been used and are rarely used. NET Ajax. jQuery has several methods to call WebService. This mainly describes the POST and GET methods. In fact, we do not recommend the GET Method for security methods, the following describes the problems caused by improper parameter settings and WebService call using jquery, as well as the causes of the problems. Here we will only discuss the returned JSON data. I believe everyone knows more about the convenience of ajax for JSON data. If you do not know anything about ajax, you can refer to this information on the Internet, I will not talk about it here, or I will write another article in this area later.

The following is the WebService server code called by jQuery.:

The WS1 and WS2 methods are POST method requests. Therefore, set UseHttpGet to false, WS3 and WS4 to GET method requests, and set UseHttpGet to true.
Copy codeThe Code is as follows:
Using System. Web. Script. Services;
Using System. Web. Services;
Namespace WebService35
{
///
/// Summary of WebService1
///
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = WsiProfiles. BasicProfile1_1)]
[System. ComponentModel. ToolboxItem (false)]
// To allow ASP. net ajax to call this Web service from a script, cancel the comments to the downstream.
[System. Web. Script. Services. ScriptService]
Public class WebService1: System. Web. Services. WebService
{
[WebMethod]
[ScriptMethod (UseHttpGet = false)]
Public string WS1 ()
{
Return "POST No parameter ";
}
[WebMethod]
[ScriptMethod (UseHttpGet = false)]
Public string WS2 (string s)
{
Return s;
}
[WebMethod]
[ScriptMethod (UseHttpGet = true)]
Public string WS3 ()
{
Return "GET no parameter ";
}
[WebMethod]
[ScriptMethod (UseHttpGet = true)]
Public string WS4 (string s)
{
Return s;
}
}
}


Copy codeThe Code is as follows:
Function fun1 (){
$. Ajax ({
Url: "WebService1.asmx/WS1 ",
Type: "POST ",
DataType: "json ",
ContentType: "application/json; charset = UTF-8 ",
Data :"",
Success: function (json ){
Alert (json. d );
},
Error: function (x, e ){
Alert (x. responseText );
},
Complete: function (x ){
Alert (x. responseText );
}
});
}


The preceding JS method uses the POST method to request the WebService method code without parameters. However, the above Code does not return the correct JSON format data, but XML format data, to enable WebService to return JSON data, set Content-Type to application/json in Request Headers. Someone has to ask, you do not set contentType to "application/json; charset = UTF-8? Yes, it is set. However, in jquery, if Content-Length is 0 or is not set, it will ignore the contentType you set. I can see the figure below, this is the data of the captured Request Headers. We can see that the Content-Length is 0 and there is no Content-Type. The WebService does not know the data we need in JSON format, it returns data in the default XML format to us. The reason is 0 because I have not submitted any data.

What should I do? Continue to look at the following JS Code. Because we call a WebService method that fails to provide parameters, we can submit an empty and JSON object "{}", as shown below, set data {}.
Copy codeThe Code is as follows:
Function fun1 (){
$. Ajax ({
Url: "WebService1.asmx/WS1 ",
Type: "POST ",
DataType: "json ",
ContentType: "application/json; charset = UTF-8 ",
Data :"{}",
Success: function (json ){
Alert (json. d );
},
Error: function (x, e ){
Alert (x. responseText );
},
Complete: function (x ){
Alert (x. responseText );
}
});
}
Now let's take a look. We can see that the Content-Length is already 2 and there is also Contetn-Type, or the value we set, in this way, the JSON data can be correctly returned for our use.

Another method is: Since jquery does not set Content-Type for us, we can set it by ourselves, as shown in the following code, before sending data, set the Content-Type to "application/json; charset = UTF-8.
Copy codeThe Code is as follows:
Function fun1 (){
$. Ajax ({
Url: "WebService1.asmx/WS1 ",
Type: "POST ",
DataType: "json ",
Data :"",
BeforeSend: function (x ){
X. setRequestHeader ("Content-Type", "application/json; charset = UTF-8 ");
},
Success: function (json ){
Alert (json. d );
},
Error: function (x, e ){
Alert (x. responseText );
},
Complete: function (x ){
Alert (x. responseText );
}
});
}

The following is the Request Headers captured after we manually set the Content-Type. We can see that even if the Content-Length is 0, the Content-Type is correct.

However, it should be noted that if we set the contentType of jquery, an empty JSON object is sent, and the Content-Type is manually set, the following code is shown:
Copy codeThe Code is as follows:
Function fun1 (){
$. Ajax ({
Url: "WebService1.asmx/WS1 ",
Type: "POST ",
DataType: "json ",
ContentType: "application/json; charset = UTF-8 ",
Data :"{}",
BeforeSend: function (x ){
X. setRequestHeader ("Content-Type", "application/json; charset = UTF-8 ");
},
Success: function (json ){
Alert (json. d );
},
Error: function (x, e ){
Alert (x. responseText );
},
Complete: function (x ){
Alert (x. responseText );
}
});
}

As shown in the Requst Headers sent by IE, you will see two Content-Type values separated by commas. Why? Because jquery sets a value for Content-Type, and we set it again manually. in IE, it sets the value of Content-Type multiple times and appends it instead of replacing it, however, this does not affect WebService's correct return of JSON data to us, but this situation should be avoided.

If the preceding Content-Type value can return JSON data correctly, the following code cannot return JSON data correctly.
Copy codeThe Code is as follows:
Function fun1 (){
$. Ajax ({
Url: "WebService1.asmx/WS1 ",
Type: "POST ",
DataType: "json ",
Data :"{}",
BeforeSend: function (x ){
X. setRequestHeader ("Content-Type", "application/json; charset = UTF-8 ");
},
Success: function (json ){
Alert (json. d );
},
Error: function (x, e ){
Alert (x. responseText );
},
Complete: function (x ){
Alert (x. responseText );
}
});
}

We can see that Content-Type has two values, but this is different from the one above. This time, the value is different. One is application/x-www-form-urlencoded, one is application/json; charset = UTF-8. In this case, the data in JSON format cannot be returned correctly. Why? This is because we have not set contentType for jquery and submitted an empty JSON object. Why does this happen when we use Content-Type? Because when jquery ajax uses the POST method to submit data, if contentType is not set and the sent data is not empty, it sets a default value for ContentType, that is, application/x-www-form-urlencoded.

Therefore, when a POST request is used, if the data is submitted, that is, when the datar attribute of jquery ajax is not empty (not empty: 1. send an empty object to call the WebService method without parameters; 2. please use a WebService method with parameters .), You must set the contentType attribute and cannot manually set the Content-Type.

The following is the WebService method with parameters in the request. Some situations have been mentioned above, so I will not talk about it here.

However, you must note that when using the POST method for request, you do not need to manually encode the parameter values with Chinese characters, as shown in the following data: "{s: 'Post has a parameter '}", you do not need to write data: "{s:" + encodeURI ('Post has parameters') +.
Copy codeThe Code is as follows:
Function fun2 (){
$. Ajax ({
Url: "WebService1.asmx/WS2 ",
ContentType: "application/json; charset = UTF-8 ",
Type: "POST ",
DataType: "json ",
Data: "{s: 'Post parameter '}",
Success: function (json ){
Alert (json. d );
},
Error: function (x, e ){
Alert (x. responseText );;
},
Complete: function (x ){
Alert (x. responseText );
}
});
}

The above is a POST request. The following is a GET request.

The following is a WebService method that uses the GET method to request a WebService without parameters. However, this is a piece of wrong code. Where is the error? You can think about it yourself. Let's talk about it together.
Copy codeThe Code is as follows:
Function fun3 (){
$. Ajax ({
Url: "WebService1.asmx/WS3 ",
Type: "GET ",
DataType: "json ",
Data :"",
ContentType: "application/json; charset = UTF-8 ",
Success: function (json ){
Alert (json. d );
},
Error: function (x, e ){
Alert (x. responseText );
},
Complete: function (x ){
Alert (x. responseText );
}
});
}

It is the Request Headers captured by the above Code Request. Let's take a look at the problem.

The following code correctly calls the WebService method without parameters using the GET method.
Copy codeThe Code is as follows:
Function fun3 (){
$. Ajax ({
Url: "WebService1.asmx/WS3 ",
DataType: "json ",
Data :"",
BeforeSend: function (x ){
X. setRequestHeader ("Content-Type", "application/json; charset = UTF-8 ");
},
Success: function (json ){
Alert (json. d );
},
Error: function (x, e ){
Alert (x. responseText );
},
Complete: function (x ){
Alert (x. responseText );
}
});
}

The following code correctly calls the WebService method with parameters using the GET method.
Copy codeThe Code is as follows:
Function fun4 (){
$. Ajax ({
Url: "WebService1.asmx/WS4 ",
DataType: "json ",
Data: encodeURI ("s = 'get parameter '"),
BeforeSend: function (x ){
X. setRequestHeader ("Content-Type", "application/json; charset = UTF-8 ");
},
Success: function (json ){
Alert (json. d );
},
Error: function (x, e ){
Alert (x. responseText );
},
Complete: function (x ){
Alert (x. responseText );
}
});
}

It is correct to use the GET method (with parameters and without parameters) to call the Request Headers captured by the WebService method.

As you can see, there is no Content-Length for requests using the GET method, whether there are parameters or no parameters, so jquery cannot set Content-Type for us, I can only set Content-Type manually, so we do not need to set the contentType of jquery ajax.

Note that the GET method is different from the POST method. When there is a parameter, if the parameter value is not an ASCII character, use encodeURI to encode it. Otherwise, the data received by the server is garbled.

Related Article

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.