本文實(shí)例為大家分享了jQuery AJAX調(diào)用頁(yè)面后臺(tái)方法,供大家參考,具體內(nèi)容如下
1.新建demo.aspx頁(yè)面。
2.首先在該頁(yè)面的后臺(tái)文件demos.aspx.cs中添加引用。
using System.Web.Services;
1).無(wú)參數(shù)的方法調(diào)用.
大家注意了,這個(gè)版本不能低于.net framework 2.0。2.0已下不支持的。
后臺(tái)代碼:
[WebMethod]
public static string SayHello()
{
return "Hello Ajax!";
}
JS代碼:
$(function() {
$("#btnOK").click(function() {
$.ajax({
//要用post方式
type: "Post",
//方法所在頁(yè)面和方法名
url: "Demo.aspx/SayHello",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
//返回的數(shù)據(jù)用data.d獲取內(nèi)容
alert(data.d);
},
error: function(err) {
alert(err);
}
});
//禁用按鈕的提交
return false;
});
});
頁(yè)面代碼:
form id="form1" runat="server">
div>
asp:Button ID="btnOK" runat="server" Text="驗(yàn)證用戶" />
/div>
/form>
運(yùn)行效果如下:
![](http://img.jbzj.com/file_images/article/201605/201659100030489.jpg?20164910037)
2).有參數(shù)方法調(diào)用
后臺(tái)代碼:
[WebMethod]
public static string GetStr(string str, string str2)
{
return str + str2;
}
JS代碼:
$(function() {
$("#btnOK").click(function() {
$.ajax({
type: "Post",
url: "demo.aspx/GetStr",
//方法傳參的寫法一定要對(duì),str為形參的名字,str2為第二個(gè)形參的名字
data: "{'str':'我是','str2':'XXX'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
//返回的數(shù)據(jù)用data.d獲取內(nèi)容
alert(data.d);
},
error: function(err) {
alert(err);
}
});
//禁用按鈕的提交
return false;
});
});
運(yùn)行效果如下:
![](http://img.jbzj.com/file_images/article/201605/201659100131248.jpg?20164910142)
3).返回?cái)?shù)組方法
后臺(tái)代碼:
[WebMethod]
public static Liststring> GetArray()
{
Liststring> li = new Liststring>();
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() {
//插入結(jié)果到li里面
$("#list").append("li>" + this + "/li>");
});
alert(data.d);
},
error: function(err) {
alert(err);
}
});
//禁用按鈕的提交
return false;
});
});
頁(yè)面代碼:
form id="form1" runat="server">
div>
asp:Button ID="btnOK" runat="server" Text="驗(yàn)證用戶" />
/div>
ul id="list">
/ul>
/form>
運(yùn)行結(jié)果圖:
![](http://img.jbzj.com/file_images/article/201605/201659100149895.jpg?20164910157)
jQuery AJAX實(shí)現(xiàn)調(diào)用頁(yè)面后臺(tái)方法就為大家介紹到這,希望對(duì)大家的學(xué)習(xí)有所啟發(fā)。
您可能感興趣的文章:- 淺談Ajax技術(shù)實(shí)現(xiàn)頁(yè)面無(wú)刷新
- jQuery中通過(guò)ajax的get()函數(shù)讀取頁(yè)面的方法
- jQuery實(shí)現(xiàn)AJAX定時(shí)刷新局部頁(yè)面實(shí)例
- ajax如何實(shí)現(xiàn)頁(yè)面局部跳轉(zhuǎn)與結(jié)果返回
- 頁(yè)面向下滾動(dòng)ajax獲取數(shù)據(jù)的實(shí)現(xiàn)方法(兼容手機(jī))