1. Create a demo. aspx page.
2. Add references to the background file demos. aspx. cs on the page.
using System.Web.Services;
3. Call a method without parameters.
Note that this version cannot be lower than. net framework 2.0. 2.0 is not supported.
Background code:
[WebMethod]
public static string SayHello()
{
return "Hello Ajax!";
}
JS Code:
$ (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:
<Form id = "form1" runat = "server">
<Div>
<Asp: Button ID = "btnOK" runat = "server" Text = "verify user"/>
</Div>
</Form>
The running effect is as follows:
3. Call methods with Parameters
Background code:
[WebMethod]
public static string GetStr(string str, string str2)
{
return str + str2;
}
JS Code:
$ (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:
[WebMethod]
public static List<string> GetArray()
{
List<string> li = new List<string>();
for (int i = 0; i < 10; i++)
li.Add(i + "");
return li;
}
JS Code:
$ (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 ("<li>" + this + "</li> ");
});
Alert (data. d );
},
Error: function (err ){
Alert (err );
}
});
// Disable button submission
Return false;
});
});
Page code:
<form id= "form1" runat= "server" > <div> <asp:Button ID= "btnOK" runat= "server" Text= "Verify the user" /> </div> <ul id= "list" > </ul> </form> |
Running result diagram: