Use jQueryAJAX to call the page background method and the web service definition method. For more information, see 1. Create a demo. aspx page.
2. Add references to the background file demos. aspx. cs on the page.
Using System. Web. Services;
3. method call without parameters. You must note that this version cannot be lower than. net framework 2.0. 2.0 is not supported.
Background code:
The Code is as follows:
[WebMethod]
Public static string SayHello ()
{
Return "Hello Ajax! ";
}
JS Code:
The Code is as follows:
$ (Function (){
$ ("# BtnOK"). click (function (){
$. Ajax ({
// Use the post Method
Type: "Post ",
// Method page and method name
Url: "Demo. aspx/SayHello ",
ContentType: "application/json; charset = UTF-8 ",
DataType: "json ",
Success: function (data ){
// Use data. d to obtain the returned data.
Alert (data. d );
},
Error: function (err ){
Alert (err );
}
});
// Disable button submission
Return false;
});
});
Page code:
The Code is as follows:
3. Call methods with Parameters
Background code:
The Code is as follows:
[WebMethod]
Public static string GetStr (string str, string str2)
{
Return str + str2;
}
JS Code:
The Code is as follows:
$ (Function (){
$ ("# BtnOK"). click (function (){
$. Ajax ({
Type: "Post ",
Url: "demo. aspx/GetStr ",
// Method parameters must be written correctly. str is the name of the parameter, and str2 is the name of the second parameter.
Data: "{'str': 'I am', 'str2': 'xxx '}",
ContentType: "application/json; charset = UTF-8 ",
DataType: "json ",
Success: function (data ){
// Use data. d to obtain the returned data.
Alert (data. d );
},
Error: function (err ){
Alert (err );
}
});
// Disable button submission
Return false;
});
});
The running effect is as follows:
4. Return Array Method
Background code:
The Code is as follows:
[WebMethod]
Public static List GetArray ()
{
List Li = new List ();
For (int I = 0; I <10; I ++)
Li. Add (I + "");
Return li;
}
JS Code:
The Code is as follows:
$ (Function (){
$ ("# BtnOK"). click (function (){
$. Ajax ({
Type: "Post ",
Url: "demo. aspx/GetArray ",
ContentType: "application/json; charset = UTF-8 ",
DataType: "json ",
Success: function (data ){
// Clear ul before insertion
$ ("# List" ).html ("");
// Recursively retrieve data
$ (Data. d). each (function (){
// Insert the result to li
$ ("# List"). append ("
"+ This +"");
});
Alert (data. d );
},
Error: function (err ){
Alert (err );
}
});
// Disable button submission
Return false;
});
});
Running result diagram: