3 pitfalls to avoid when applying jquery to asp.net ajax

Source: Internet
Author: User

The benefit of using JSON as a lightweight data type communication in Ajax is clear that, given security concerns, ASP.net Ajax webservice using JSON should prevent JSON hijacking. So it is usually our practice to use the POST request type and set the requested Content-type to Application/json; Charset=utf-8. But the client if you are using jquery, there are three detail issues that we should be aware of:

1: If we post without any data to the server, please specify data:{} such as:

Code

1 $.ajax({
2  type: "POST",
3  url: "PageMethod.aspx/PageMethodName",
4  data: "{}",//注意这里不可省。
5  contentType: "application/json; charset=utf-8",
6  dataType: "json"
7 });

This is because content-length must be provided when post requests are in IIS, and even if no post data.content-length should be set to 0, then jquery will not automatically set headers unless the request contains post Data. And ASP.net Ajax's JSON transfer, which requires post, so we can't change the way he asks. The simple solution is to give an empty JSON object in the request. To meet the requirements of IIS, this time Content-length is 2. At this point in the server I can completely ignore this null parameter and handle the corresponding request.

2: When the post data is not empty. We should avoid setting up Requestheader in the Beforesend event.

If the example post data is empty, if jquery cannot set the header automatically, can we help him set it by hand? When the answer is

Yes, I do. At this point we were set in the Beforesend event. As shown in the code (please note: must be set to Application/json otherwise webservice

does not return JSON. This is also due to security considerations.

Code

1 $.ajax({
2  type: "POST",
3  url: "WebService.asmx/WebMethodName",
4  beforeSend: function(xhr) {
5   xhr.setRequestHeader("Content-type",
6             "application/json; charset=utf-8");
7  },
8  dataType: "json"
9 });

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.