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 = ""/> </div> <ul id = "list"> </ul> </form>
Running result diagram: