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.