jQuery AJAX實現(xiàn)調用頁面后臺方法
本文實例為大家分享了jQuery AJAX調用頁面后臺方法,供大家參考,具體內容如下
1.新建demo.aspx頁面。
2.首先在該頁面的后臺文件demos.aspx.cs中添加引用。
using System.Web.Services;
1).無參數(shù)的方法調用.
大家注意了,這個版本不能低于.net framework 2.0。2.0已下不支持的。
后臺代碼:
[WebMethod] public static string SayHello() { return "Hello Ajax!"; }
JS代碼:
$(function() { $("#btnOK").click(function() { $.ajax({ //要用post方式 type: "Post", //方法所在頁面和方法名 url: "Demo.aspx/SayHello", contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { //返回的數(shù)據(jù)用data.d獲取內容 alert(data.d); }, error: function(err) { alert(err); } }); //禁用按鈕的提交 return false; }); });
頁面代碼:
<form id="form1" runat="server"> <div> <asp:Button ID="btnOK" runat="server" Text="驗證用戶" /> </div> </form>
運行效果如下:
2).有參數(shù)方法調用
后臺代碼:
[WebMethod] public static string GetStr(string str, string str2) { return str + str2; }
JS代碼:
$(function() { $("#btnOK").click(function() { $.ajax({ type: "Post", url: "demo.aspx/GetStr", //方法傳參的寫法一定要對,str為形參的名字,str2為第二個形參的名字 data: "{'str':'我是','str2':'XXX'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { //返回的數(shù)據(jù)用data.d獲取內容 alert(data.d); }, error: function(err) { alert(err); } }); //禁用按鈕的提交 return false; }); });
運行效果如下:
3).返回數(shù)組方法
后臺代碼:
[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代碼:
$(function() { $("#btnOK").click(function() { $.ajax({ type: "Post", url: "demo.aspx/GetArray", contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { //插入前先清空ul $("#list").html(""); //遞歸獲取數(shù)據(jù) $(data.d).each(function() { //插入結果到li里面 $("#list").append("<li>" + this + "</li>"); }); alert(data.d); }, error: function(err) { alert(err); } }); //禁用按鈕的提交 return false; }); });
頁面代碼:
<form id="form1" runat="server"> <div> <asp:Button ID="btnOK" runat="server" Text="驗證用戶" /> </div> <ul id="list"> </ul> </form>
運行結果圖:
jQuery AJAX實現(xiàn)調用頁面后臺方法就為大家介紹到這,希望對大家的學習有所啟發(fā)。
相關文章
jquery ajax實現(xiàn)批量刪除具體思路及代碼
回調函數(shù),在請求完成后需要進行的操作:此處是把選中的checkbox去掉,接下來為大家詳細介紹下,感興趣的朋友可以參考下哈,希望對你有所幫助2013-04-04Ajax調用restful接口傳送Json格式數(shù)據(jù)的方法
這篇文章主要介紹了Ajax調用restful接口傳送Json格式數(shù)據(jù)的方法的相關資料,非常不錯,具有參考借鑒價值,感興趣的朋友一起看下吧2016-07-07