JQuery AJAX calls the page background method, jqueryajax
This example shares the jQuery AJAX call page background Method for your reference. The details are as follows:
1. Create a demo. aspx page.
2. Add references to the background file demos. aspx. cs on the page.
Using System. Web. Services;
1). method call 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) {// data is returned. d. Obtain the content alert (data. d) ;}, error: function (err) {alert (err) ;}}); // return false when the disabled button is submitted ;});});
Page code:
<Form id = "form1" runat = "server"> <div> <asp: button ID = "btnOK" runat = "server" Text = ""/> </div> </form>
The running effect is as follows:
2). There are parameter method calls
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 ", // The method for passing parameters must be correct. str is the name of the form parameter, and str2 is the name of the second form parameter data:" {'str ': 'I am', 'str2': 'xxx'} ", contentType:" application/json; charset = UTF-8 ", dataType:" json ", success: function (data) {// The returned data uses data. d. Obtain the content alert (data. d) ;}, error: function (err) {alert (err) ;}}); // return false when the disabled button is submitted ;});});
The running effect is as follows:
3). returns the 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 $ ("# list" ).html ("") before insertion; // recursively obtain data $ (data. d ). each (function () {// Insert the result to li $ ("# list "). append ("<li>" + this + "</li>") ;}); alert (data. d) ;}, error: function (err) {alert (err) ;}}); // return false when the disabled button is submitted ;});});
Page code:
<Form id = "form1" runat = "server"> <div> <asp: button ID = "btnOK" runat = "server" Text = ""/> </div> <ul id = "list"> </ul> </form>
Running result diagram:
JQuery AJAX calls the page back-end method to introduce it to you, hoping to inspire your learning.