1. Create a new demo.aspx page.
2. First, add a reference to the background file Demos.aspx.cs of the page.
Using System.Web.Services;
3. Method calls without parameters. As you are aware, this version should not be less than the. NET Framework 2.0. 2.0 has not been supported.
Background code:
Copy Code code as follows:
[WebMethod]
public static string SayHello ()
{
Return "Hello ajax!";
}
JS Code:
Copy Code code as follows:
$ (function () {
$ ("#btnOK"). Click (function () {
$.ajax ({
To use the Post method
Type: "Post",
Method contains the page and method name
URL: "Demo.aspx/sayhello",
ContentType: "Application/json; Charset=utf-8 ",
DataType: "JSON",
Success:function (data) {
The returned data gets content with DATA.D
alert (DATA.D);
},
Error:function (Err) {
alert (ERR);
}
});
Disable submit for a button
return false;
});
});
Page code:
Copy Code code as follows:
<form id= "Form1" runat= "Server" >
<div>
<asp:button id= "Btnok" runat= "Server" text= "authenticate users"/>
</div>
</form>
3. Parameter method call
Background code:
Copy Code code as follows:
[WebMethod]
public static string Getstr (String str, string str2)
{
return str + str2;
}
JS Code:
Copy Code code as follows:
$ (function () {
$ ("#btnOK"). Click (function () {
$.ajax ({
Type: "Post",
URL: "Demo.aspx/getstr",
Method must be written to the reference, STR is the name of the formal parameter, STR2 is the name of the second formal parameter.
Data: "{' str ': ' I am ', ' str2 ': ' XXX '}",
ContentType: "Application/json; Charset=utf-8 ",
DataType: "JSON",
Success:function (data) {
The returned data gets content with DATA.D
alert (DATA.D);
},
Error:function (Err) {
alert (ERR);
}
});
Disable submit for a button
return false;
});
});
The operation effect is as follows:
4. Return Array method
Background code:
Copy Code code as follows:
[WebMethod]
public static list<string> GetArray ()
{
list<string> li = new list<string> ();
for (int i = 0; i < i++)
Li. ADD (i + "");
return Li;
}
JS Code:
Copy Code code 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 inserting
$ ("#list"). HTML ("");
Recursive fetch data
$ (DATA.D). each (function () {
Insert results into Li inside
$ ("#list"). Append ("<li>" + This + "</li>");
});
alert (DATA.D);
},
Error:function (Err) {
alert (ERR);
}
});
Disable submit for a button
return false;
});
});
Run the result diagram: