如下介紹Jquery中 Post Get Ajax幾種異步請求的使用方法
javascript
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Jquery異步請求.WebForm1" %> 2 3 <!DOCTYPE html> 4 5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 8 <script src="jquery-2.0.3.js" type="text/javascript"></script> 9 <title></title> 10 <script type="text/javascript"> 11 $(function () { 12 // $.post("Student.ashx", "", function () { },"json"); 13 14 $("#btn").click(function () { 15 var id = $("#stuID").val(); 16 17 18 //data: 返回的數據:XML/JSON/HTML等 19 //textStatus: 請求狀態:success/error/notmodified/timeout 4種 20 21 //$.get("GetStudent.ashx", {"id":id}, function (data, textStatus) { 22 // $.each(data, function (i,value) { 23 // alert(value["Name"]); 24 // }); 25 26 //},"json"); 27 28 29 30 // $.post("GetStudent.ashx", {"id": id}, function (data, textStatus) { 31 // $.each(data, function (i,item) { 32 // alert(item.Name); 33 // }); 34 // },"json"); 35 //}) 36 37 38 //alert(responseText);//請求返回的內容 39 //alert(textStatus);//請求狀態:success,error 40 //alert(XMLHttpRequest);//XMLHttpRequest對象 41 //全局事件是每次的Ajax請求都會觸發的, 42 $.ajax({ 43 url: "GetStudent.ashx", //發送請求的地址 44 type: "Get", //請求方式GET/POST,默認GET 45 dataType: "json", //預期服務器返回的數據類型 46 global: true, //是否觸發全局Ajax事件,默認爲true(觸發) 47 data: { "id": id }, //向服務器發送的數據 48 beforeSend: function (XMLHttpRequest) { 49 //alert("正在加載中"); 50 $("#div1").show(); 51 52 }, ///發送請求前調用,能夠放一些"正在加載"之類額話 53 complete: function (XMLHttpRequest, textStatus) { 54 55 }, //請求完成時(成功或失敗) 56 success: function (data, textStatus) //請求成功後的回調函數 57 { 58 $("#div1").hide(); 59 $.each(data, function (i, item) //i: data中對象成員或數組的索引值 60 //item: data對應的變量或內容 61 { 62 alert(item.Name); 63 64 }); 65 66 }, 67 error: function (XMLHttpRequest, txtStatus, ErroeThrown) { } //失敗後回調 68 }); 69 70
71 72 //fn指回調函數(callback) 73 ajaxStart(fn) 74 ajaxStop(fn) 75 ajaxComplete(fn) 76 ajaxError(fn) 77 ajaxSend(fn) 78 ajaxSuccess(fn) 79 //若是想某個Ajax請求不受全局方式影響 80 $.ajax({ 81 global: false 82 }) 83 84 85 })}) 86 </script> 87 88 <style type="text/css"> 89 .login{width:200px;border:0px solid #ccc;display:none;position:absolute;top:200px;left:500px;z-index:200} 90 </style> 91 </head> 92 <body> 93 <form id="form1" runat="server"> 94 <div id="div1" class="login"> 95 <img src="1.gif" /> 96 </div> 97 <input type="text" id="stuID" /><br /> 98 <input type="button" value="點擊按鈕" id="btn" /> 99 </form> 100 </body> 101 </html>