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'