$. Post, $. ajax: The frontend sends asynchronous requests to the background.
1. $. ajax
By default, this method uses the GET method to pass data. If the [data] parameter passes data in, it is automatically converted to the POST method.
$ (Function (){
Var appointment = {
Name: "galen. guo ",
Age: 20
};
$ ('# Tty'). click (function (){
Var url = 'testjson ';
// The foreground transmits a json serialized object to the action
$. Ajax ({
Url: '@ Url. Action ("TestJson ")',
Type: 'post', // specify the POST method
Data: JSON. stringify (appointment), // serialize the object to json format and cannot be omitted
DataType: 'json', // data format
ProcessData: false,
ContentType: 'application/json; charset = UTF-8 ',
Success: function (data ){
Alert ('OK ');
}
});
});
});
---- ProcessData: (default: true) by default, the sent data is converted to an object (technically not a string) with the default content type "application/x-www-form-urlencoded ". If you want to send the DOM tree information or other information that does not want to be converted, set it to false.
Background code:
Public class Appointment
{
Public String Name {get; set ;}
Public String Age {get; set ;}
}
[HttpPost]
Public JsonResult TestJson (Appointment app)
{
Return Json ("");
}
2. $. post
Original form: jQuery. post (url, [data], [callback], [type]): asynchronous request using POST
[Type] parameter: (Optional) Type of data to be sent. The default value is string, which can be specified as JSON, XML, etc.
Usage: $. post (url, {userId: userId, "key": keyValue}, function (data) {}); // parameters passed to action are in the form of a health value pair, data is the value returned by action. In this example, it is "hello world"
The url specifies the action to be called, for example, '@ Url. Action ("Test ")',
Test action Declaration:
[HttpPost]
Public JsonResult Test (Int32 userId, String key)
{
.........................
Return ("hello world ");
}
In fact, $. post is implemented by $. ajax. The source code is as follows:
Function (url, data, callback, type ){
If (jQuery. isFunction (data )){
Callback = data;
Data = {};
}
Return jQuery. ajax ({
Type: "POST ",
Url: url,
Data: data,
Success: callback,
DataType: type
});