How to use jquery post to pass data with special characters _ajax related

Source: Internet
Author: User

In jquery, we typically use $.ajax or $.post for data delivery, but it's not usually possible to pass special characters such as "<." This article describes how to pass this data with special characters.

1, prepare the page and control-side code

The page code is as follows:

<script type= "Text/javascript" >
  $ (function () {
      $ ("#btnSet"). Click (function () {
        var a = $ ("# TxtValue "). Val ();
        var data = {Name:a};
        alert (data);
        $.ajax ({
          URL: ' @Url. Action ("MyTest") ',
          type: ' Post ',
          dataType: ' json ',
          Data:data,
        })
      ;
    }
  );
</script>
 
 

The background code is as follows:

  Public ActionResult MyTest (studentinfo stu)
    {return
      Content ("OK");
    }

Where studentinfo is defined as follows:

  public class Studentinfo
  {public
    string Name {get; set;}
  }

2. Test data transmission

When we pass ordinary data, everything is fine.

However, when you enter data that contains special characters, it is not delivered to the background normally.

3, processing methods

If you decide that you want to pass special characters, you need to adjust the jquery code, and the following request code is as follows:

<script type= "Text/javascript" >
  $ (function () {
      $ ("#btnSet"). Click (function () {
        var a = $ ("# TxtValue "). Val ();
        var data = json.stringify ({name:a});
        alert (data);
        $.ajax ({
          URL: ' @Url. Action ("MyTest") ',
          type: ' Post ',
          dataType: ' json ',
          Data:data,
          ContentType: ' Application/json '
        });
      };
</script>

There are two main points of adjustment:

Serializes the JSON data to be passed Json.stringify
New parameters in $.ajax request: ContentType: ' Application/json '

Well, the above is the whole of this article, I hope you like.

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.