jquery Call WebService return JSON data and parameter settings attention problem _ practical Tips

Source: Internet
Author: User
The release of the. NET Framework 3.5 resolves the JSON problem in the WebService invocation, and this article describes the jquery call WebService returns JSON data based on the. NET Framework 3.5. In addition, we should also introduce the problem of setting up and improper setting of the parameters of WebService with jquery, and the cause of the problem.

jquery Call WebService Online introduction is also more, the recent project I also used a lot of, has been very rarely used. NET Ajax, more in favor of jquery call request WebService There are several ways, this is mainly about the post and get method, In fact, the security method is not recommended to use the Get method, the following is the use of jquery invoke WebService parameter settings and improper settings of the problem, there are problems. We only discuss the return of JSON data, I believe that we are more understanding of JSON format data for AJAX convenience, do not understand the Internet can look for this information to look at, here is not to say, or I later write an article in this regard.

here is the jquery call WebService server-side code :

WS1 and WS2 methods that are requested by the Post method, set WS4 to True for the method requested by FALSE,WS3 and Usehttpget for the Get method.

Copy Code code as follows:

Using System.Web.Script.Services;
Using System.Web.Services;
Namespace WebService35
{
///
Summary description of WebService1
///
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = wsiprofiles.basicprofile1_1)]
[System.ComponentModel.ToolboxItem (False)]
To allow the use of ASP.net AJAX to invoke this Web service from a script, uncomment the downlink.
[System.Web.Script.Services.ScriptService]
public class WebService1:System.Web.Services.WebService
{
[WebMethod]
[Scriptmethod (Usehttpget = False)]
public string WS1 ()
{
Return "post without parameters";
}
[WebMethod]
[Scriptmethod (Usehttpget = False)]
public string WS2 (string s)
{
return s;
}
[WebMethod]
[Scriptmethod (Usehttpget = True)]
public string WS3 ()
{
Return "Get no parameters";
}
[WebMethod]
[Scriptmethod (Usehttpget = True)]
public string WS4 (string s)
{
return s;
}
}
}


Copy Code code 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 above JS method requests the code of the WebService method with the Post method, but the above code does not return the correct JSON-formatted data, but instead returns the XML-formatted data back to the data that is to be used to return the JSON format to the WebService, in the request Headers set Content-type for Application/json, someone to ask, you do not set the contenttype for "Application/json;" Charset=utf-8 "? Yes, it's set, but in jquery, if Content-length is 0 or not set, it ignores the contenttype you set, and I can look at the graph below, which is the data of the request headers that crawled, You can see that content-length is 0 and there is no content-type, and WebService doesn't know we need JSON format data, it returns the default XML format data to us, 0 because I didn't submit any data.

What's going to happen? Continue to look at the following JS code, because we are calling a WebService method of not able to parameter, so we can submit a null and JSON object "{}", as shown below, set data to {}.

Copy Code code 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 I'm going to take a look at the diagram and see that the content-length is already 2 and there are contetn-type, or the values we set, so that we can return the JSON data correctly for us to use.

There is another way: since jquery does not give us the content-type, we can set it ourselves, as shown in the following code, we set the Content-type to "Application/json" before sending the data; Charset=utf-8, "so be it.

Copy Code code 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 our manual set up after the Content-type grab request Headers, you can see, even if the content-length is 0, inside also have the right content-type.

However, it should be noted that if we set up the contenttype of jquery and send an empty JSON object, and also set the Content-type manually, as shown in the following code:

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

So the requst headers sent in IE as shown in the following illustration, you will see that Content-type has two values separated by commas, why? Because jquery set a value for Content-type, we set it up manually again, and in IE is set content-type value multiple times it will append, not replace, but this does not affect webservice correctly returns JSON data to us, However, this should be avoided.

If the above set two times Content-type value can return the JSON data correctly, the following code will not return the JSON data correctly.

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

From the figure below you can see that Content-type also has two values, but this and the above is a bit different, this time this value is not the same, one is application/x-www-form-urlencoded, one is Application/json; Charset=utf-8, this situation does not correctly return JSON-formatted data. Why is that? This is because we did not set contenttype for jquery and submitted an empty JSON object, so why would you use Content-type? Because jquery Ajax uses the Post method to submit data, if the contenttype is not set and the data sent is not empty, it sets a default value for ContentType, which is application/ X-www-form-urlencoded, so this will happen.

So, in the case of a POST method request, if there is a submission, that is, the jquery Ajax Datar property is not empty: 1. Send an empty object to invoke the WebService method without parameters; 2. Please have a parameter WebService method. , be sure to set the ContentType property, and you cannot set the content-type manually.

Here is the request with the parameter of the WebService method, some cases are also mentioned above, there is no more to say.

But one thing to be aware of, is to use the Post method request, do not have to manually encode the parameters of the Chinese characters, such as the following data: "{s: ' Post has parameters '}", you do not have to write data: "{s:" +encodeuri (' Post has parameters ') + "}".

Copy Code code as follows:

function fun2 () {
$.ajax ({
URL: "Webservice1.asmx/ws2",
ContentType: "Application/json; Charset=utf-8 ",
Type: "POST",
DataType: "JSON",
Data: "{s: ' Post has parameter '}",
Success:function (JSON) {
alert (JSON.D);
},
Error:function (x, E) {
alert (x.responsetext);;
},
Complete:function (x) {
alert (X.responsetext);
}
});
}

The above is what we said with the Post method request, and the following is requested using the Get method.

Here is a GET method to request a WebService method without parameters, but this is a bad code, where is wrong, the children's shoes can think for themselves, we say together below.

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

The following figure is a request to crawl using the above code requests Headers, we look at the problem is where.

The following code is the correct way to invoke the WebService method with the Get method.

Copy Code code 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 is the correct way to call a WebService method with a parameter using the Get method.
Copy Code code as follows:

function Fun4 () {
$.ajax ({
URL: "Webservice1.asmx/ws4",
DataType: "JSON",
Data:encodeuri ("s= ' Get has Parameters '"),
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 figure is the correct request Headers that is crawled by invoking the WebService method using the Get method (with parameters and no parameters).

As you can see from the figure above, using the Get method request, whether there are parameters or no parameters, there is no content-length, so jquery can not set content-type for us, I can only manually set Content-type, So there's no need to set up jquery Ajax contenttype.

Note that the Get method is different from the post method, when there are parameters, if the value of the parameter is not an ASCII character, you need to use encodeURI to edit the code, or the server received the data is garbled.

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.