Jquery. Post (URL, [data], [callback]) loads information through a remote http post request. This is a simple POST Request function to replace complex $. Ajax. You can call the callback function when the request is successful. To execute a function when an error occurs, use $. Ajax.
Return Value
XMLHttpRequest
Parameters
URL(String): The sending request address.
Data(MAP): (optional) Key/value parameter to be sent.
Callback(Function): (optional) callback function when sending successfully.
Example: use $. Post () to calculate the sum of two numbers and the result of multiplication (return JSON.
Index.html page JSCodeFragment:
Code
$ ( " # Btn_1 " ). Click ( Function (){
// Verify
If ($ ( " # Txt_1 " ). Val () = '' | $ ( " # Txt_2 " ). Val () = '' )
{
Alert ( ' Enter the value to calculate ' );
Return False ;
}
// Request result from ADD. ashx
$. Post ( ' Enumerate/Add. ashx ' ,{
// Parameter 1
Num1: $ ( ' # Txt_1 ' ). Val (),
// Parameter 2
Num2: $ ( " # Txt_2 " ). Val ()
},
// Callback Function
Function (Theback)
{
// Output result
$ ( " # Span_1 " ). Text (theback );
},
// Return type
" Text "
);
});
Add. ashx Page code (calculation and return results ):
Code
<% @ Webhandler Language = " C # " Class = " Add " %>
UsingSystem;
UsingSystem. Web;
Public Class Add: ihttphandler {
Public Void Processrequest (httpcontext context ){
// Return type
Context. response. contenttype = " Text/html " ;
// Receiving Parameters
Int Inum1, inum2;
Int . Tryparse (context. request [ " Num1 " ]. Tostring (), Out Inum1 );
Int . Tryparse (context. request [ " Num2 " ]. Tostring (), Out Inum2 );
// Calculate and return results
Context. response. Write ( " Result: " + (Inum1 + Inum2). tostring ());
}
Public Bool Isreusable {
Get {
Return False ;
}
}
}
$. Post () return JSON method usage:
Code
$ ( " # Btn_2 " ). Click ( Function (){
// Verify
If ($ ( " # Txt_3 " ). Val () = '' | $ ( " # Txt_4 " ). Val () = '' )
{
Alert ( ' Enter the value to calculate ' );
Return False ;
}
// Request results to multiply. ashx
$. Post ( ' Enumerate/multiply. ashx ' ,{
// Parameter 1
Num1: $ ( ' # Txt_3 ' ). Val (),
// Parameter 2
Num2: $ ( " # Txt_4 " ). Val ()
},
// Callback Function
Function (Theback)
{
// Output result
$ ( " # Div_2 " Pai.html ( ' Number 1: ' + Theback. num1 + ' <Br/> ' + ' Number 2: ' + Theback. num2 + ' <Br/> ' + ' AlgorithmType: ' + Theback. Type + ' <Br/> ' + ' Calculation Result: ' + Theback. Result );
},
// Return type
" JSON "
);
});
C # Return the JSON code (multiply. ashx page ):
Code
Context. response. contenttype = " Application/JSON " ;
Int Inum1, inum2;
Int . Tryparse (context. request [ " Num1 " ]. Tostring (), Out Inum1 );
Int . Tryparse (context. request [ " Num2 " ]. Tostring (), Out Inum2 );
Context. response. Write ( " {Num1 :' " + Inum1.tostring () + " ', Num2 :' " + Inum2.tostring () + " ', Type: 'enumerate', result :' " + (Inum1 * Inum2). tostring () + " '} " );
download Source Code : Download