How to Use jQuery post to transmit data with special characters, jquery special characters

Source: Internet
Author: User

How to Use jQuery post to transmit data with special characters, jquery special characters

In jQuery, $. ajax or $. post is usually used for data transmission and processing, but special characters such as "<" cannot be passed here ". This article describes how to pass data with special characters.

1. Prepare the page and control 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");        }

StudentInfo is defined as follows:

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

2. Test Data Transmission

When we pass normal data, everything is normal.

However, data with special characters cannot be transmitted to the background normally.

3. Handling Method

If you are sure to pass special characters, you need to adjust the jQuery code. The adjusted 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 major adjustments:

  • Serialize json. stringify the JSON data to be passed
  • Add the parameter contentType: 'application/json' to the $. ajax request'

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.