JQuery中的Ajax(六)

來源:互聯網
上載者:User

標籤:

一:Ajax請求
jQuery.ajax(options)
load(url,[data],[callback])
jQuery.get(url,[data],[callback])
jQuery.getJSON(url,[data],[callback])
jQuery.getScript(url,[callback])
jQuery.post(url,[data],[callback])

 


1.jQuery.ajax(options)
通過 HTTP 要求載入遠端資料。
jQuery 底層 AJAX 實現。 返回其建立的 XMLHttpRequest 對象。大多數情況下你無需直接操作該對象,但特殊情況下可用於手動終止請求。
$.ajax() 只有一個參數:參數 key/value 對象,包含各配置及回呼函數資訊。
注意1: 如果你指定了 dataType 選項,請確保伺服器返回正確的 MIME 資訊,(如 xml 返回 "text/xml")。錯誤的 MIME 類型可能導致不可預知的錯誤

注意2:如果dataType設定為"script",那麼所有的遠程(不在同一網域名稱下)的POST請求都將轉化為GET請求。(因為將使用DOM的script標籤來載入)
傳回值
XMLHttpRequest
參數
options (可選) : AJAX 請求設定。所有選項都是可選的。
選項
async (Boolean) : (預設: true) 預設設定下,所有請求均為非同步請求。如果需要發送同步請求,請將此選項設定為 false。注意,同步請求將鎖住瀏覽器,使用者其它操作必須等待請求完成才可以執行。
beforeSend (Function) : 發送請求前可修改 XMLHttpRequest 對象的函數,如添加自訂 HTTP 頭。XMLHttpRequest 對象是唯一的參數。
      function (XMLHttpRequest) {
    this; // 調用本次AJAX請求時傳遞的options參數

}

 

cache (Boolean) : (預設: true,dataType為script時預設為false) jQuery 1.2 新功能,設定為 false 將不會從瀏覽器緩衝中載入請求資訊。
complete (Function) : 請求完成後回呼函數 (請求成功或失敗時均調用)。參數: XMLHttpRequest 對象和一個描述成功請求類型的字串。
    function (XMLHttpRequest, textStatus) {
   this; // 調用本次AJAX請求時傳遞的options參數
}
contentType (String) : (預設: "application/x-www-form-urlencoded") 發送資訊至伺服器時內容編碼類別型。預設值適合大多數應用場合。
data (Object,String) : 發送到伺服器的資料。將自動轉換為請求字串格式。GET 請求中將附加在 URL 後。查看 processData 選項說明以禁止此自動轉換。必須為 Key/Value 格式。如果為數組,jQuery 將自動為不同值對應同一個名稱。如 {foo:["bar1", "bar2"]} 轉換為 ‘&foo=bar1&foo=bar2‘。

dataType (String) : 預期伺服器返回的資料類型。如果不指定,jQuery 將自動根據 HTTP 包 MIME 資訊返回 responseXML 或 responseText,並作為回呼函數參數傳遞,可用值:
"xml": 返回 XML 文檔,可用 jQuery 處理。
"html": 返回純文字 HTML 資訊;包含 script 元素。
"script": 返回純文字 JavaScript 代碼。不會自動緩衝結果。除非設定了"cache"參數
"json": 返回 JSON 資料 。

 

error (Function) : (預設: 自動判斷 (xml 或 html)) 請求失敗時調用時間。參數:XMLHttpRequest 對象、錯誤資訊、(可選)捕獲的錯誤對象。Ajax 事件。
function (XMLHttpRequest, textStatus, errorThrown) {
   // 通常 textStatus 和 errorThrown 之中
    // 只有一個會包含資訊
   this; // 調用本次AJAX請求時傳遞的options參數
}

樣本
載入並執行一個 JS 檔案。
jQuery 代碼:
$.ajax({
 type: "GET", 
url: "test.js",
  dataType: "script"
});
儲存資料到伺服器,成功時顯示資訊。
jQuery 代碼:
$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
});

裝入一個 HTML 網頁最新版本。jQuery 代碼:$.ajax({
  url:"test.html",
  cache: false,
  success: function(html){
    $("#results").append(html);
  }
}); 同步載入資料。發送請求時鎖住瀏覽器。需要鎖定使用者互動操作時使用同步方式。 jQuery 代碼: var html =$.ajax({
  url:"some.php",
  async:false
 }).responseText;  

 

二、jQuery.get(url,[data],[callback])
通過遠程 HTTP GET 請求載入資訊。
這是一個簡單的 GET 請求功能以取代複雜 $.ajax 。請求成功時可調用回呼函數。如果需要在出錯時執行函數,請使用 $.ajax。
傳回值
XMLHttpRequest
參數
url (String) : 待載入頁面的URL地址
data (Map) : (可選) 待發送 Key/value 參數。
callback (Function) : (可選) 載入成功時回呼函數。

 

樣本
請求 test.php 網頁,忽略傳回值。
jQuery 代碼:
$.get("test.php");
請求 test.php 網頁,傳送2個參數,忽略傳回值。
jQuery 代碼:
$.get("test.php", { name: "John", time: "2pm" } );

顯示 test.php 傳回值(HTML 或 XML,取決於傳回值)。
jQuery 代碼:
$.get("test.php", function(data){
  alert("Data Loaded: " + data);
});
顯示 test.cgi 傳回值(HTML 或 XML,取決於傳回值),添加一組請求參數。
jQuery 代碼:
$.get("test.cgi", { name: "John", time: "2pm" },
  function(data){
    alert("Data Loaded: " + data);
  });

三:jQuery.getJSON(url,[data],[callback])
通過 HTTP GET 請求載入 JSON 資料。

注意:此行以後的代碼將在這個回呼函數執行前執行。
傳回值
XMLHttpRequest
參數
url (String) : 發送請求地址。
data (Map) : (可選) 待發送 Key/value 參數。
callback (Function) : (可選) 載入成功時回呼函數

 

樣本
從 Flickr JSONP API 載入 4 張最新的關於貓的圖片。
HTML 程式碼:
<div id="images"></div>
jQuery 代碼:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",function(data){
  $.each(data.items, function(i,item){
    $("<img/>").attr("src",
item.media.m).appendTo("#images");
    if ( i == 3 ) return false;
 });
});

從 test.js 載入 JSON 資料並顯示 JSON 資料中一個 name 欄位資料。
jQuery 代碼:
$.getJSON("test.js", function(json){
  alert("JSON Data: " + json.users[3].name);
});
從 test.js 載入 JSON 資料,附加參數,顯示 JSON 資料中一個 name 欄位資料。
jQuery 代碼:
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json){
  alert("JSON Data: " + json.users[3].name);
});

 

四:jQuery.getScript(url,[callback])
通過 HTTP GET 請求載入並執行一個 JavaScript 檔案。
jQuery 1.2 版本之前,getScript 只能調用同域 JS 檔案。 1.2中,您可以跨域調用 JavaScript 檔案。注意:Safari 2 或更早的版本不能在全域範圍中同步執行指令碼。如果通過 getScript 加入指令碼,請加入延時函數。
傳回值
XMLHttpRequest
參數
url (String) : 待載入 JS 檔案地址。
callback (Function) : (可選) 成功載入後回呼函數。

樣本
載入 jQuery 官方顏色動畫外掛程式 成功後綁定顏色變化動畫。
HTML 程式碼:
<button id="go">» Run</button>
<div class="block"></div>
jQuery 代碼:
jQuery.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js",
function(){
  $("#go").click(function(){
    $(".block").animate( { backgroundColor: ‘pink‘ }, 1000)
      .animate( { backgroundColor: ‘blue‘ }, 1000);
  });
});

 


載入並執行 test.js。
jQuery 代碼:
$.getScript("test.js");
載入並執行 test.js ,成功後顯示資訊。
jQuery 代碼:
$.getScript("test.js", function(){
 alert("Script loaded and executed.");
});

五 :jQuery.post(url,[data],[callback])
通過遠程 HTTP POST 請求載入資訊。
這是一個簡單的 POST 請求功能以取代複雜 $.ajax 。請求成功時可調用回呼函數。如果需要在出錯時執行函數,請使用 $.ajax。
傳回值
XMLHttpRequest
參數
url (String) : 發送請求地址。
data (Map) : (可選) 待發送 Key/value 參數。
callback (Function) : (可選) 發送成功時回呼函數。

代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title></title> <!--   引入jQuery -->    <script src="../scripts/jquery-1.2.6.js" type="text/javascript"></script>  <script src="../scripts/jquery-1.2.6-vsdoc-cn.js" type="text/javascript"></script> <script type="text/javascript">     $(document).ready(function() {         $("#btnLogin").click(function() {                         var params = $("#form1").serialize();                         alert(params);                         $.ajax(                         {                             type: "GET",                             url: "/Demo/LoginHandler.aspx",                             data:params,                             success: function(data) {                                 alert(data);                             }                         })            $.get("/Demo/LoginHandler.aspx",{txtUser:$("#txtUser").val(),txtPass:$("#txtPass").val()} ,function(data) {                alert(data);                     });         $.getJSON("/Demo/LoginHandler.aspx", { txtUser: $("#txtUser").val(), txtPass: $("#txtPass").val() }, function(josn) {         alert(josn.success);                    });         })     }) </script></head><body >   <form id="form1">       <p> <input id="txtUser" name="txtUser" type="text" /></p>           <p> <input id="txtPass" name="txtPass" type="password" /></p>            <input id="btnLogin" type="button" value="登入" />   </form></body></html> 

 

實現大量刪除:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="19-2.aspx.cs" Inherits="T19_jQuery中的Ajax應用初步_19_2" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title></title>   <script src="../scripts/jquery-1.2.6.js" type="text/javascript"></script>  <script src="../scripts/jquery-1.2.6-vsdoc-cn.js" type="text/javascript"></script>  <script type="text/javascript">      $(document).ready(function() {          $("#chkAll").click(function() {              var isSelected = this.checked;              $(":checkbox").each(function() {                  this.checked = isSelected;              })          })          $("#btnDel").click(function() {              //alert($(":checkbox[checked]").length);              //alert($("#GridView1").html());              var ids = [];              $(":checkbox[checked]").each(function() {                  var id = $(this).parent().attr("title");                  if (id) ids.push(id);              })              //alert(ids);              $.getJSON("/Demo/AjaxT19.aspx", { ids: ids }, function(josn) {                  alert(josn.success);              });          });      })  </script></head><body>    <form id="form1" runat="server">    <div>            <asp:GridView ID="GridView1" runat="server" AllowPaging="True"             AutoGenerateColumns="False" CellPadding="4" DataKeyNames="Id"             DataSourceID="SqlDataSource1" EmptyDataText="沒有可顯示的資料記錄。" ForeColor="#333333"             GridLines="None" Width="669px">            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />            <Columns>                <asp:TemplateField>                    <ItemTemplate>                        <asp:CheckBox ID="CheckBox1" runat="server" ToolTip=‘<%# Eval("Id") %>‘ />                    </ItemTemplate>                    <HeaderTemplate>                        <input ID="chkAll"  type="checkbox" />                    </HeaderTemplate>                </asp:TemplateField>                <asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True"                     SortExpression="Id" />                <asp:BoundField DataField="Au_Id" HeaderText="Au_Id" SortExpression="Au_Id" />                <asp:BoundField DataField="Au_Lname" HeaderText="Au_Lname"                     SortExpression="Au_Lname" />                <asp:BoundField DataField="Au_Fname" HeaderText="Au_Fname"                     SortExpression="Au_Fname" />                <asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />                <asp:BoundField DataField="Addr" HeaderText="Addr" SortExpression="Addr" />                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />                <asp:BoundField DataField="State" HeaderText="State" SortExpression="State" />                <asp:BoundField DataField="Zip" HeaderText="Zip" SortExpression="Zip" />            </Columns>            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />            <EditRowStyle BackColor="#999999" />            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />        </asp:GridView>        <asp:SqlDataSource ID="SqlDataSource1" runat="server"             ConnectionString="<%$ ConnectionStrings:JQuerySimpleDBConnectionString1 %>"             DeleteCommand="DELETE FROM [Author] WHERE [Id] = @Id"             InsertCommand="INSERT INTO [Author] ([Au_Id], [Au_Lname], [Au_Fname], [Phone], [Addr], [City], [State], [Zip]) VALUES (@Au_Id, @Au_Lname, @Au_Fname, @Phone, @Addr, @City, @State, @Zip)"             ProviderName="<%$ ConnectionStrings:JQuerySimpleDBConnectionString1.ProviderName %>"             SelectCommand="SELECT [Id], [Au_Id], [Au_Lname], [Au_Fname], [Phone], [Addr], [City], [State], [Zip] FROM [Author]"             UpdateCommand="UPDATE [Author] SET [Au_Id] = @Au_Id, [Au_Lname] = @Au_Lname, [Au_Fname] = @Au_Fname, [Phone] = @Phone, [Addr] = @Addr, [City] = @City, [State] = @State, [Zip] = @Zip WHERE [Id] = @Id">            <DeleteParameters>                <asp:Parameter Name="Id" Type="Int32" />            </DeleteParameters>            <InsertParameters>                <asp:Parameter Name="Au_Id" Type="String" />                <asp:Parameter Name="Au_Lname" Type="String" />                <asp:Parameter Name="Au_Fname" Type="String" />                <asp:Parameter Name="Phone" Type="String" />                <asp:Parameter Name="Addr" Type="String" />                <asp:Parameter Name="City" Type="String" />                <asp:Parameter Name="State" Type="String" />                <asp:Parameter Name="Zip" Type="String" />            </InsertParameters>            <UpdateParameters>                <asp:Parameter Name="Au_Id" Type="String" />                <asp:Parameter Name="Au_Lname" Type="String" />                <asp:Parameter Name="Au_Fname" Type="String" />                <asp:Parameter Name="Phone" Type="String" />                <asp:Parameter Name="Addr" Type="String" />                <asp:Parameter Name="City" Type="String" />                <asp:Parameter Name="State" Type="String" />                <asp:Parameter Name="Zip" Type="String" />                <asp:Parameter Name="Id" Type="Int32" />            </UpdateParameters>        </asp:SqlDataSource>        </div>    </form>    <p>        <input id="btnDel" type="button" value="大量刪除" /></p></body></html>

 後台代碼:

protected void Page_Load(object sender, EventArgs e)    {        if (Request["ids"] != null)        {            string ids = Request.QueryString["ids"];            string strsql = "delete from Employee where id in (" + ids + ")";            Response.Write("{success:true}");        }        else            Response.Write("{success:false}");    }

 

JQuery中的Ajax(六)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.