Function prototype: $. post (url, params, callback)
UrlIs the submitted address. For example:"Sample. ashx"
ParamsYes. For example:{Name: "xxx", id: "001 "}
CallbackIs the callback function. For example:Function (msg) {alert (msg );}
NOTE 1: In sample. the Section ashx uses context. request ["id"] and context. request ["name"] to obtain the "001" and "xxx" respectively, instead of using context. request. queryString ["id"]
Note 2: The callback function is triggered after the return value of the server. Therefore, you do not need to determine xmlHttp. readyState = 4 & xmlHttp. status = 200.
Next, we will use a piece of code to compare the $. post method with the original xmlHttp method.
For better matching, I have two methods to implement the same function. The passed value is the same as the callback function name.
/* XmlHttp mode */
Var xmlHttp; // define the object xmlHttp
Function createXMLHttpRequest () // create an xmlHttpRequest function
{
If (window. ActiveXObject)
{
XmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ");
}
Else if (window. XMLHttpRequest)
{
XmlHttp = new XMLHttpRequest ();
}
}
Function btn_onclick () // assume that a button is clicked to trigger this ajax
{
CreateXMLHttpRequest ();
Var url = "sample. ashx? Id = 1 & name = a "; // assume that the parameter is passed to sample. ashx, and two values, id = 1 and name =
XmlHttp. open ("POST", url, true );
XmlHttp. onreadystatechange = Response; // The callback function is Response ()
XmlHttp. send (null );
}
Function Response ()
{
If (xmlHttp. readyState = 4 & xmlHttp. status = 200)
{
Alert (xmlHttp. responseText); // a dialog box is displayed, showing the content returned by the server.
}
}
/* $. Post Method */
Function btn_onclick () // This event and function are also triggered after it is clicked.
{
/*
Sample. ashx, also id = 1 & name =
The function (msg) Here is the callback function. You can directly write the executed content in {}. msg indicates the data returned by the server.
To better match the above method, I still want him to call Response here, but the parameter msg needs to be added.
*/
$. Post ("sample. ashx", {id: "1", name: "a"}, function (msg) {Response (msg );});
}
Function Response (msg)
{
Alert (msg); // a dialog box is displayed, showing the content returned by the server.
}