jQuery AJAX實(shí)現(xiàn)調(diào)用頁(yè)面后臺(tái)方法
1.新建demo.aspx頁(yè)面。
2.首先在該頁(yè)面的后臺(tái)文件demos.aspx.cs中添加引用。
using System.Web.Services;
3.無(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)行效果如下:
3.有參數(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", //方法傳參的寫(xiě)法一定要對(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)行效果如下:
4.返回?cái)?shù)組方法
后臺(tái)代碼:
[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() { //插入結(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é)果圖:
致勝軟件
因?yàn)橥ㄓ密浖木窒扌远淖兤髽I(yè)經(jīng)營(yíng)方式?
那這是反人類的。!
致勝軟件根據(jù)需求定制,永遠(yuǎn)為您而變!
致勝網(wǎng)絡(luò)的理念
面對(duì)面給客戶最實(shí)在的 最貼心的服務(wù)!
強(qiáng)大的技術(shù)團(tuán)隊(duì),過(guò)百的案例與經(jīng)驗(yàn)!
在三線城市開(kāi)發(fā),按三線城市等級(jí)收費(fèi)!
致勝網(wǎng)絡(luò)介紹
2009年成立,至今7年。!
7年的專業(yè),7年之癢!
期待可以為您提供長(zhǎng)期服務(wù)!
想進(jìn)一步了解
歡迎您的咨詢?
QQ:1990654
微信:13592986386
電話:13592986386

騰訊微博
新浪微博