Jquery calls WebService Based on. NET Framework 3.5 to return JSON data

Source: Internet
Author: User

Jquer has introduced many WebService calls on the internet, and I have used many of them in recent projects. net Ajax, more interested in jquery, there are several methods to call the WebService, this mainly refers to the post and get methods, in fact, the security method is not recommended to use the get method, the following describes the problems caused by improper parameter settings and WebService call using jquery, as well as the causes of the problems. We will only discuss the returned data in JSON format here. I believe you are familiar with the convenience of JSON data for Ajax, if you do not know about shoes, you can refer to this information on the Internet. I will not talk about it here, or I will write another article about this.Article.

Below is the WebService ServerCode:

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.

 Using System. Web. Script. Services; Using System. Web. Services; Namespace Webservice35 { /// <Summary>  /// Summary of webservice1  /// </Summary> [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 " No parameter for post ";} [Webmethod] [scriptmethod (usehttpget = False )] Public   String WS2 ( String S ){ Return S;} [webmethod] [scriptmethod (usehttpget = True )] Public   String Ws3 (){ Return " Get has no parameters ";} [Webmethod] [scriptmethod (usehttpget = True )] Public  String Ws4 ( String S ){ Return S ;}}}

 

 
FunctionFun1 () {$. Ajax ({URL :"Webservice1.asmx/WS1", Type :"Post", Datatype :"JSON", Contenttype :"APP/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 {}.

FunctionFun1 () {$. Ajax ({URL :"Webservice1.asmx/WS1", Type :"Post", Datatype :"JSON", Contenttype :"APP/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, data in JSON format 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.

FunctionFun1 () {$. Ajax ({URL :"Webservice1.asmx/WS1", Type :"Post", Datatype :"JSON", Data :"", Beforesend:Function(X) {X. setRequestHeader ("Content-Type","APP/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, note that if we set the contenttype of jquery, an empty JSON object is sent, and the Content-Type is also manually set, the following code is used:

  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 to return data in the correct JSON format to us, but this situation should be avoided.

If the preceding Content-Type value can return JSON data correctly, the following code cannot return data correctly.

  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 a parameter ') + "}.

FunctionFun2 () {$. Ajax ({URL :"Webservice1.asmx/WS2", Contenttype :"APP/JSON; charset = UTF-8", Type :"Post", Datatype :"JSON", Data :"{S: 'Post has a 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.

FunctionFun3 () {$. Ajax ({URL :"Webservice1.asmx/ws3", Type :"Get", Datatype :"JSON", Data :"", Contenttype :"APP/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.

FunctionFun3 () {$. Ajax ({URL :"Webservice1.asmx/ws3", Datatype :"JSON", Data :"", Beforesend:Function(X) {X. setRequestHeader ("Content-Type","APP/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.

FunctionFun4 () {$. Ajax ({URL :"Webservice1.asmx/ws4", Datatype :"JSON", Data: encodeuri ("S = 'get has a parameter'"), Beforesend:Function(X) {X. setRequestHeader ("Content-Type","APP/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.

In addition, this article is original. If you want to reprint it, please indicate the source.

Code address: http://download.csdn.net/source/1510113.

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.