Jquery ajax 学习笔记
?本人的js & jq 一直是菜鳥級別,最近不忙就看了看ajax方面的知識,文中部分內(nèi)容參考自這里&這里?之前一直用js寫ajax現(xiàn)在基于jq實現(xiàn)方便多了~
$.get & $.post 和 $.ajax的區(qū)別
之前看過同事寫過$.post,而我一直用$.ajax,后來才知道$.get()和$.post()都是通過get和post方式來進(jìn)行異步,$.ajax()說是jquery最底層的ajax實現(xiàn)的,這里我們使用$.ajax的方式實現(xiàn).
調(diào)用無參方法
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //調(diào)用無參方法 $("#Button1").click(function () { ????$.ajax({ ????????//要用post方式????? ????????type:?"Post", ????????//方法所在頁面和方法名????? ????????url:?"About.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("Error: "?+ err); ????????} ????}); }) |
| 1 2 3 4 5 6 | [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public?static?string?SayHello() { ????return?"Hello Ajax!"; } |
這里只列出常用的$.ajax的屬性以及方法詳情請參考這里
有點類似類似調(diào)用WebService,后臺方法必須為static,訪問范圍為protect/public,
WebMethod特性是必須的,這樣才能被客戶端腳本調(diào)用,支持遠(yuǎn)程調(diào)用.
ScriptMethod特性是可選的,用于指定調(diào)用方法的 HTTP 謂詞(GET 或 POST),以及指定輸出格式(JSON或XML)沒有此特性,方法則默認(rèn)只能被HTTP POST方式調(diào)用,并且輸出將序列化為 JSON.
Asp.net 3.5以上可直接使用以上兩個命名空間,Asp.net 2.0需安裝Asp.net Ajax,或者單獨引用Asp.net Ajax的System.Web.Extensions.dll.
如后臺方法無參數(shù),data項可填為"{}"或者直接省略.Asp.net 3.5以上使用返回值,需要加上".d",如以上代碼里的"data.d",Asp.net 2.0直接使用"data"就行了.原因可能是兩者序列化的方法有所不同.
調(diào)用有參方法
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | //調(diào)用返回有參方法 $(function () { ????$("#Button2").click(function () { ????????$.ajax({ ????????????type:?"Post", ????????????url:?"About.aspx/Hello", ????????????//方法傳參的寫法一定要對,name為形參的名字,age為第二個形參的名字????? ????????????data:?"{'name':'chenxu','age':'21'}", ????????????contentType:?"application/json; charset=utf-8", ????????????dataType:?"json", ????????????success: function (data) { ????????????????//返回的數(shù)據(jù)用data.d獲取內(nèi)容????? ????????????????alert(data.d); ????????????}, ????????????error: function (err) { ????????????????alert("Error: "?+ err); ????????????} ????????}); ????}); }); |
| 1 2 3 4 5 6 | [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public?static?string?Hello(string?name,?string?age) { ????return?string.Format("hello my name is {0}, {1} years old.", name, age); } |
調(diào)用返回集合方法
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | //調(diào)用返回集合方法 $("#Button3").click(function () { ????$.ajax({ ????????type:?"Post", ????????url:?"About.aspx/GetList", ????????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("Error: "?+ err); ????????} ????}); }); |
| 1 2 3 4 5 6 7 8 9 10 11 | [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public?static?List<string> GetList() { ????List<string> list =?new?List<string> ????{ ????????"a","b","c","d","e","f" ????}; ????return?list; } |
調(diào)用返回實體方法
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | $("#Button4").click(function () { ????$.ajax({ ????????type:?"Post", ????????url:?"About.aspx/GetPerson", ????????contentType:?"application/json; charset=utf-8", ????????dataType:?"json", ????????success: function (data) { ????????????$(data.d).each(function () { ????????????????alert(this["name"]); ????????????}) ????????}, ????????error: function (err) { ????????????alert("Error: "?+ err); ????????} ????}); }); |
| 1 2 3 4 5 6 | [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public?static?Person GetPerson() { ????return?new?Person { name =?"chenxu"?}; } |
| 1 2 3 4 | public?class?Person { ????public?string?name {?get;?set; } } |
調(diào)用返回DATASET
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | //調(diào)用返回DATASET方法 $('#Button5').click(function () { ????$.ajax({ ????????type:?"POST", ????????url:?"WebService.asmx/GetDataSet", ????????//data: "{}", ????????dataType:?'xml',?//返回的類型為XML ????????success: function (result) {?//成功時執(zhí)行的方法 ????????????//捕獲處理過程中的異常并輸出 ????????????try?{ ????????????????$(result).find("Table1").each(function () { ????????????????????alert($(this).find("Id").text() +?" "?+ $(this).find("Value").text()); ????????????????}); ????????????} ????????????catch?(e) { ????????????????alert(e); ????????????????return; ????????????} ????????}, ????????error: function (result, status) {?//出錯時會執(zhí)行這里的回調(diào)函數(shù) ????????????if?(status ==?'error') { ????????????????alert(status); ????????????} ????????} ????}); }); |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | [WebMethod] //[ScriptMethod(ResponseFormat = ResponseFormat.Xml)] public?static?DataSet GetDataSet() { ????DataSet ds =?new?DataSet(); ????DataTable dt =?new?DataTable(); ????dt.Columns.Add("ID", Type.GetType("System.String")); ????dt.Columns.Add("Value", Type.GetType("System.String")); ???????????? ????DataRow dr = dt.NewRow(); ????dr["ID"] =?"1"; ????dr["Value"] =?".NET"; ????dt.Rows.Add(dr); ????dr = dt.NewRow(); ????dr["ID"] =?"2"; ????dr["Value"] =?"JAVA"; ????dt.Rows.Add(dr); ????ds.Tables.Add(dt); ????return?ds; } |
調(diào)用dataset總是出問題,之前記得這樣寫是好用的,找了好長時間沒找到問題,哪位大神找到了告訴我.
把web form里面的方法GetDataSet放到web service(asmx)中 并設(shè)定?contentType:?"text/xml;?charset=utf-8",dataType:?'xml'?
調(diào)用ASHX?一般處理程序
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | //調(diào)用ASHX 一般處理程序 $("#Button6").click(function () { ????$.ajax({ ????????type:?"Post", ????????url:?"Hello.ashx", ????????contentType:?"application/json; charset=utf-8", ????????dataType:?"html",?//此處需要寫成html ????????success: function (data) { ????????????alert(data); ????????}, ????????error: function (err) { ????????????alert("Error: "?+ err); ????????} ????}); }); |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | /// <summary> /// Hello 的摘要說明 /// </summary> public?class?Hello : IHttpHandler { ????public?void?ProcessRequest(HttpContext context) ????{ ????????context.Response.ContentType =?"text/plain"; ????????context.Response.Write("Hello World"); ????????context.Response.End(); ????} ????public?bool?IsReusable ????{ ????????get ????????{ ????????????return?false; ????????} ????} } |
完整code
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | <%@ Page Title="主頁"?Language="C#"?MasterPageFile="~/Site.master"?AutoEventWireup="true" ????CodeBehind="Default.aspx.cs"?Inherits="JqueryAjax._Default"?%> <asp:Content ID="HeaderContent"?runat="server"?ContentPlaceHolderID="HeadContent"> ????<script src="Scripts/jquery-1.4.1.js"?type="text/javascript"></script> ????<script type="text/javascript"> ????????$(function () { ????????????//調(diào)用無參方法 ????????????$("#Button1").click(function () { ????????????????$.ajax({ ????????????????????//要用post方式????? ????????????????????type:?"Post", ????????????????????//方法所在頁面和方法名????? ????????????????????url:?"About.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("Error: "?+ err); ????????????????????} ????????????????}); ????????????}) ????????????//調(diào)用返回有參方法 ????????????$(function () { ????????????????$("#Button2").click(function () { ????????????????????$.ajax({ ????????????????????????type:?"Post", ????????????????????????url:?"About.aspx/Hello", ????????????????????????//方法傳參的寫法一定要對,str為形參的名字,str2為第二個形參的名字????? ????????????????????????data:?"{'name':'chenxu','age':'21'}", ????????????????????????contentType:?"application/json; charset=utf-8", ????????????????????????dataType:?"json", ????????????????????????success: function (data) { ????????????????????????????//返回的數(shù)據(jù)用data.d獲取內(nèi)容????? ????????????????????????????alert(data.d); ????????????????????????}, ????????????????????????error: function (err) { ????????????????????????????alert("Error: "?+ err); ????????????????????????} ????????????????????}); ????????????????}); ????????????}); ????????????//調(diào)用返回集合方法 ????????????$("#Button3").click(function () { ????????????????$.ajax({ ????????????????????type:?"Post", ????????????????????url:?"About.aspx/GetList", ????????????????????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("Error: "?+ err); ????????????????????} ????????????????}); ????????????}); ????????????//調(diào)用返回實體方法 ????????????$("#Button4").click(function () { ????????????????$.ajax({ ????????????????????type:?"Post", ????????????????????url:?"About.aspx/GetPerson", ????????????????????contentType:?"application/json; charset=utf-8", ????????????????????dataType:?"json", ????????????????????success: function (data) { ????????????????????????$(data.d).each(function () { ????????????????????????????alert(this["name"]); ????????????????????????}) ????????????????????}, ????????????????????error: function (err) { ????????????????????????alert("Error: "?+ err); ????????????????????} ????????????????}); ????????????}); ????????????//調(diào)用返回DATASET方法 ????????????$('#Button5').click(function () { ????????????????$.ajax({ ????????????????????type:?"POST", ????????????????????url:?"WebService.asmx/GetDataSet", ????????????????????//data: "{}", ????????????????????dataType:?'xml',?//返回的類型為XML ????????????????????success: function (result) {?//成功時執(zhí)行的方法 ????????????????????????//捕獲處理過程中的異常并輸出 ????????????????????????try?{ ????????????????????????????$(result).find("Table1").each(function () { ????????????????????????????????alert($(this).find("Id").text() +?" "?+ $(this).find("Value").text()); ????????????????????????????}); ????????????????????????} ????????????????????????catch?(e) { ????????????????????????????alert(e); ????????????????????????????return; ????????????????????????} ????????????????????}, ????????????????????error: function (result, status) {?//出錯時會執(zhí)行這里的回調(diào)函數(shù) ????????????????????????if?(status ==?'error') { ????????????????????????????alert(status); ????????????????????????} ????????????????????} ????????????????}); ????????????}); ????????????//調(diào)用ASHX 一般處理程序 ????????????$("#Button6").click(function () { ????????????????$.ajax({ ????????????????????type:?"Post", ????????????????????url:?"Hello.ashx", ????????????????????contentType:?"application/json; charset=utf-8", ????????????????????dataType:?"html",?//此處需要寫成html ????????????????????success: function (data) { ????????????????????????alert(data); ????????????????????}, ????????????????????error: function (err) { ????????????????????????alert("Error: "?+ err); ????????????????????} ????????????????}); ????????????}); ????????}) ????</script> </asp:Content> <asp:Content ID="BodyContent"?runat="server"?ContentPlaceHolderID="MainContent"> ????<h2> ????????ASP.NET Jquery Ajax 調(diào)用后臺方法示例. ????</h2> ????<input id="Button1"?type="button"?value="調(diào)用無參方法"?/> ????<input id="Button2"?type="button"?value="調(diào)用有參方法"?/> ????<input id="Button3"?type="button"?value="調(diào)用返回集合方法"?/> ????<input id="Button4"?type="button"?value="調(diào)用返回實體方法"?/> ????<input id="Button5"?type="button"?value="調(diào)用返回DATASET方法"?/> ????<input id="Button6"?type="button"?value="調(diào)用ASHX"?/> ????<ul id="list"> ????</ul> </asp:Content> |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | using?System; using?System.Collections.Generic; using?System.Linq; using?System.Web; using?System.Web.UI; using?System.Web.UI.WebControls; using?System.Web.Services; using?System.Web.Script.Services; using?System.Data; namespace?JqueryAjax { ????public?partial?class?About : System.Web.UI.Page ????{ ????????protected?void?Page_Load(object?sender, EventArgs e) ????????{ ????????} ????????[WebMethod] ????????[ScriptMethod(ResponseFormat = ResponseFormat.Json)] ????????public?static?string?SayHello() ????????{ ????????????return?"Hello Ajax!"; ????????} ????????[WebMethod] ????????[ScriptMethod(ResponseFormat = ResponseFormat.Json)] ????????public?static?string?Hello(string?name,?string?age) ????????{ ????????????return?string.Format("hello my name is {0}, {1} years old.", name, age); ????????} ????????[WebMethod] ????????[ScriptMethod(ResponseFormat = ResponseFormat.Json)] ????????public?static?List<string> GetList() ????????{ ????????????List<string> list =?new?List<string> ???? { ???????? "a","b","c","d","e","f" ???? }; ????????????return?list; ????????} ????????[WebMethod] ????????[ScriptMethod(ResponseFormat = ResponseFormat.Json)] ????????public?static?Person GetPerson() ????????{ ????????????return?new?Person { name =?"chenxu"?}; ????????} ????} ????public?class?Person ????{ ????????public?string?name {?get;?set; } ????} } |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | using?System; using?System.Collections.Generic; using?System.Linq; using?System.Web; using?System.Web.Services; namespace?JqueryAjax { ????/// <summary> ????/// Hello 的摘要說明 ????/// </summary> ????public?class?Hello : IHttpHandler ????{ ????????public?void?ProcessRequest(HttpContext context) ????????{ ????????????context.Response.ContentType =?"text/plain"; ????????????context.Response.Write("Hello World"); ????????????context.Response.End(); ????????} ????????public?bool?IsReusable ????????{ ????????????get ????????????{ ????????????????return?false; ????????????} ????????} ????} } |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | using?System; using?System.Collections.Generic; using?System.Linq; using?System.Web; using?System.Web.Services; using?System.Data; /// <summary> ///WebService 的摘要說明 /// </summary> [WebService(Namespace =?"http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] //若要允許使用 ASP.NET AJAX 從腳本中調(diào)用此 Web 服務(wù),請取消對下行的注釋。 // [System.Web.Script.Services.ScriptService] public?class?WebService : System.Web.Services.WebService { ????public?WebService() ????{ ????} ????[WebMethod] ????public?DataSet GetDataSet() ????{ ????????DataSet ds =?new?DataSet(); ????????DataTable dt =?new?DataTable(); ????????dt.Columns.Add("Id", Type.GetType("System.String")); ????????dt.Columns.Add("Vlues", Type.GetType("System.String")); ????????DataRow dr = dt.NewRow(); ????????dr["Id"] =?"小花"; ????????dr["Vlues"] =?"aaaaaaaaa"; ????????dt.Rows.Add(dr); ????????dr = dt.NewRow(); ????????dr["Id"] =?"小兵"; ????????dr["Vlues"] =?"bbbbbbbbb"; ????????dt.Rows.Add(dr); ????????ds.Tables.Add(dt); ????????return?ds; ????} } |
總結(jié)
一開始對data.d的這個d不是很理解,感謝這篇文章的博主,相比較與aspx ?ashx只能通過ProcessRequest方法進(jìn)行輸出而不能在內(nèi)部寫static method,如果想在ashx中使用session只要實現(xiàn)IRequiresSessionState接口即可,要不然獲取到session會為null.
轉(zhuǎn)載于:https://www.cnblogs.com/yangwujun/p/4660344.html
總結(jié)
以上是生活随笔為你收集整理的Jquery ajax 学习笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 新开了微博,小伙伴们可以关注下哦
- 下一篇: 小波说雨燕 第三季 构建 swift U