This example for you to share the jquery Ajax call page background method for your reference, the specific contents are as follows
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;
1. A method call without parameters.
Note that this version cannot be below the. NET Framework 2.0. 2.0 has not been supported.
Background code:
[WebMethod]
public static string SayHello ()
{return
"Hello ajax!";
}
JS Code:
$ (function () {
$ ("#btnOK"). Click (function () {
$.ajax ({
///To Post method
type: Post),
//method on page and method name
URL: "Demo.aspx/sayhello",
contentType: "Application/json;" Charset=utf-8 ",
dataType:" JSON ",
success:function (data) {
///returned to get Content
alert (DATA.D) with DATA.D;
} ,
error:function (err) {
alert (err);
}
});
Disable the commit of the button return
false;}
);
Page code:
<form id= "Form1" runat= "Server" > <div> <asp:button id= "Btnok" runat= "
Server" text= "Authenticate users"/ >
</div>
</form>
The operation effect is as follows:
2). Parameter method call
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 The writing of the parameter must be to, STR is the name of the formal parameter, STR2 is the name of the second formal parameter
: "{' str ': ' I am ', ' str2 ': ' XXX '}",
ContentType: " Application/json; Charset=utf-8 ",
dataType:" JSON ",
success:function (data) {
///returned to get Content
alert (DATA.D) with DATA.D;
} ,
error:function (err) {
alert (err);
}
});
Disable submit return False for button;
The operation effect is as follows:
3). Return Array method
Background code:
[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:
$ (function () {
$ ("#btnOK"). Click (function () {
$.ajax ({
type: Post),
URL: "Demo.aspx/getarray" ,
contentType: "Application/json; Charset=utf-8 ",
dataType:" JSON ",
success:function (data) {
//before inserting the UL
$ (" #list "). HTML (" ");
Recursively gets the data
$ (DATA.D). each (function () {
//insert result into Li
$ ("#list"). Append ("<li>" + This + "</li > ");
alert (DATA.D);
},
error:function (err) {
alert (err);
}
);
Disable the commit of the button return
false;}
);
Page code:
<form id= "Form1" runat= "Server" > <div> <asp:button id= "Btnok" runat= "
Server" text= "Authenticate users"/ >
</div>
<ul id= "list" >
</ul>
</form>
Run the result diagram:
JQuery Ajax implementation of the call page background method for everyone to introduce to this, I hope that the learning of everyone inspired.