Home >Web Front-end >JS Tutorial >How to use jQuery post to pass data containing special characters
In jquery, we usually use $.ajax or $.post to solve data transfer processing, but special characters are usually not allowed to be passed here, such as: "<". This article will help you solve how to pass this For data containing special characters, interested friends can take a look at it
In jQuery, we usually use $.ajax or $.post for data transfer processing, but special characters cannot usually be transferred here, such as: " <". This article introduces how to pass this kind of data containing 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> <h2>Index</h2> <input type="text" id="txtValue"/><input type="button" value="设置" id="btnSet"/>
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 transfer
When we transfer ordinary data, everything is normal.
But when data containing special characters is entered, it cannot be passed to the background normally.
3. Processing 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 main adjustments:
Serialize the json data to be passed JSON.stringify
Add new parameters in the $.ajax request :contentType:'application/json'
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Ajax asynchronous submission data return value line wrapping problem example analysis
Ajax request return data Sequence problem analysis
Solution to prevent repeated sending of Ajax requests
##
The above is the detailed content of How to use jQuery post to pass data containing special characters. For more information, please follow other related articles on the PHP Chinese website!