標籤:
Ajax結構:
var name = $("#text_1").val(); $.ajax({ url: "Ashxs/Handler.ashx",//一般處理常式路徑 data: { "name": name },//要傳輸的資料,冒號前面是鍵名後面是要傳輸的資料,如果有多條資料在大括弧內用逗號拼接 type: "post",//傳輸方式 dataType: "json",//返回資料類型 success: function (has) {//has是自訂的,必須有 if (has.hasname == "1") {//hasname是一般處理常式返回資料的鍵名 $("#span_1").text("使用者名稱已存在!"); } else { $("#span_1").text("使用者名稱可用!"); } } });error:function(){ //伺服器串連不上,或是返回內容有錯誤,就走這裡 //通常可以使用這玩意排錯 }beforeSend:function(){ //ajax一執行,就立馬執行這個方法 }complete:function(){ //ajax裡的success或是error執行完畢,立馬執行這裡 }
json基本結構:
"{\"hasname\":\"1\"}""[{"name":"zhangsan","pwd":"1234"},{"name":"lisi","pwd":"12345"}]"//就是一個字串,冒號前面是鍵名後面是資料,如果有多條資料用逗號拼接,然後用英文的中括弧括起來
三級聯動小練習:
一般處理常式:
1 DataClassesDataContext DC = new DataClassesDataContext(); 2 public void ProcessRequest(HttpContext context) 3 { 4 int count = 0; 5 string end = "["; 6 var list = DC.ChinaStates.Where(r => r.ParentAreaCode == context.Request["Pplace"]); 7 foreach (ChinaStates C in list) 8 { 9 if (count == 0)10 {11 end += "{\"place\":\"" + C.AreaName + "\",\"Pcode\":\"" + C.AreaCode + "\"}";12 }13 else14 {15 end += ",{\"place\":\"" + C.AreaName + "\",\"Pcode\":\"" + C.AreaCode + "\"}";16 }17 count++;18 }19 end += "]";20 context.Response.Write(end);
html頁面:
<select id="select_1"></select> <select id="select_2"></select> <select id="select_3"></select> <script> $.ajax({ url: "Ashxs/Handler2.ashx", data: { "Pplace": "0001" }, type: "post", dataType: "json", success: function (da) { for (i in da) { var OP = new Option(da[i].place, da[i].Pcode); $("#select_1").get(0).add(OP); } place1(); } });//顯示全部省級資料 $("#select_1").change(function () { place1() }); $("#select_2").change(function () { place2() }); function place1() { $("#select_2").empty(); $.ajax({ url: "Ashxs/Handler2.ashx", data: { "Pplace": $("#select_1").val() }, type: "post", dataType: "json", success: function (da) { for (i in da) { $("#select_2").get(0).add(new Option(da[i].place, da[i].Pcode)); } place2(); } }); }//顯示市級資料 function place2() { $("#select_3").empty(); $.ajax({ url: "Ashxs/Handler2.ashx", data: { "Pplace": $("#select_2").val() }, type: "post", dataType: "json", success: function (da) { for (i in da) { $("#select_3").get(0).add(new Option(da[i].place, da[i].Pcode)); } } }); }//顯示縣級資料 </script>
完整的Ajax及三級聯動小練習