標籤:jquery ajax
jQuery 庫擁有完整的 Ajax 相容套件。其中的函數和方法允許我們在不重新整理瀏覽器的情況下從伺服器載入資料。
jQuery 採用了三層封裝:最底層的封裝方法為:$.ajax(),而通過這層封裝了第二層有三種方法:.load()、$.get()和$.post(),最高層是$.getScript()和$.getJSON()方法。
| 函數 |
描述 |
| jQuery.ajax() |
執行非同步 HTTP (Ajax) 請求。 |
| .ajaxComplete() |
當 Ajax 請求完成時註冊要調用的處理常式。這是一個 Ajax 事件。 |
| .ajaxError() |
當 Ajax 請求完成且出現錯誤時註冊要調用的處理常式。這是一個 Ajax 事件。 |
| .ajaxSend() |
在 Ajax 請求發送之前顯示一條訊息。 |
| jQuery.ajaxSetup() |
設定將來的 Ajax 請求的預設值。 |
| .ajaxStart() |
當首個 Ajax 請求完成開始時註冊要調用的處理常式。這是一個 Ajax 事件。 |
| .ajaxStop() |
當所有 Ajax 請求完成時註冊要調用的處理常式。這是一個 Ajax 事件。 |
| .ajaxSuccess() |
當 Ajax 請求成功完成時顯示一條訊息。 |
| jQuery.get() |
使用 HTTP GET 請求從伺服器載入資料。 |
| jQuery.getJSON() |
使用 HTTP GET 請求從伺服器載入 JSON 編碼資料。 |
| jQuery.getScript() |
使用 HTTP GET 請求從伺服器載入 JavaScript 檔案,然後執行該檔案。 |
| .load() |
從伺服器載入資料,然後把返回到 HTML 放入匹配元素。 |
| jQuery.param() |
建立數組或對象的序列化表示,適合在 URL 查詢字串或 Ajax 請求中使用。 |
| jQuery.post() |
使用 HTTP POST 請求從伺服器載入資料。 |
| .serialize() |
將表單內容序列化為字串。 |
| .serializeArray() |
序列化表單元素,返回 JSON 資料結構資料。 |
1、load()方法
load()方法通過 AJAX 請求從伺服器載入資料,並把返回的資料放置到指定的元素中。.load()方法是局部方法,需要一個包含元素的jQuery對象作為首碼。
文法格式:
load(url,data,function(response,status,xhr))
參數說明:
url:必須,請求html檔案的url 地址,參數類型為String
data:可選,發送的key/value 資料,參數類型為Object
function(response,status,xhr):可選,成功或失敗的回呼函數,參數類型為函數Function。
response - 包含來自請求的結果資料;status - 包含請求的狀態("success", "notmodified", "error", "timeout" 或 "parsererror");xhr - 包含 XMLHttpRequest 對象。
備忘:XMLHttpRequest對象屬於JavaScript 範疇,可以調用一些屬性如下:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/2F/03/wKioL1OeeFLDFEKPAAEFO6-1H6E897.jpg" title="快照4.jpg" alt="wKioL1OeeFLDFEKPAAEFO6-1H6E897.jpg" />
xhr對象的status屬性的值,如果成功返回資料則為:success,否則為:error。xhr對象的statusText屬性值如下:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/2F/03/wKiom1OeeV_x-OKBAAGDk4DGcsU160.jpg" title="快照5.jpg" alt="wKiom1OeeV_x-OKBAAGDk4DGcsU160.jpg" />
範例:
--讓Ajax非同步載入一段HTML內容,若不選擇data參數,採用get方式提交,否則為post方式提交
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title>Ajax學習</title> <script type="text/javascript" src="jquery-1.11.1.min.js"></script> <script type="text/javascript"> $(function(){ $(‘input‘).click(function(){ $(‘#box1‘).load(‘test1.html .title‘,{username:‘qing‘}); $(‘#box2‘).load(‘test2.html‘); }); }); </script></head><body> <input type="button" value="Ajax載入資料" /> <div id="box1"></div> <hr color="red"> <div id="box2"></div></body></html>
test1.html檔案:
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title></title></head><body> <span class="title">新疆大學</span> <span class="url">www.xju.edu.cn</span></body></html>
test2.html檔案:
<span class="title">新疆大學</span><span class="url">www.xju.edu.cn</span>
輸出結果:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/2E/E6/wKioL1OdgiXDNDP9AAJXMOgp0s0639.jpg" title="快照2.jpg" alt="wKioL1OdgiXDNDP9AAJXMOgp0s0639.jpg" />
--讓Ajax非同步載入伺服器檔案
Ajax1.htm檔案:
<!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> <title>Ajax學習</title> <script type="text/javascript" src="jquery-1.11.1.min.js"></script> <script type="text/javascript"> $(function () { $(‘input‘).click(function () { $(‘#box1‘).load(‘http://localhost:5567/WebForm1.aspx?id=123‘, { username: ‘qing‘ }, function (response, status, xhr) { alert(‘返回的值為:‘ + response + ‘,狀態為:‘ + status + ‘,狀態是:‘ + xhr); //console.dir(xhr); //console.log("xhr:", xhr); }); }); }); </script></head><body> <input type="button" value="Ajax載入資料" /> <div id="box1"></div> </body></html>
WebForm1.aspx檔案:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %><!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></head><body> <form id="form1" runat="server"> <div> <asp:Label ID="lblMessage" runat="server" Text="Label"></asp:Label> </div> </form></body></html>
WebForm1.aspx.cs檔案:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace WebApplication1{ public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lblMessage.Text = "Hello,Ajax!" + Request["id"].ToString(); } }}
輸出結果如下:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/2F/04/wKiom1OeenDBUxldAAFIuRCbRwQ244.jpg" title="快照6.jpg" alt="wKiom1OeenDBUxldAAFIuRCbRwQ244.jpg" />
2、$.get()和$.post()
$.get()和$.post()是全域方法,無須指定某個元素。對於用途而言,.load()適合做靜態檔案的非同步擷取,而對於需要傳遞參數到伺服器頁面的,$.get()和$.post()更加合適。
$.get()方法通過遠程 HTTP GET 請求載入資訊。這是一個簡單的 GET 請求功能以取代複雜 $.ajax 。請求成功時可調用回呼函數。如果需要在出錯時執行函數,請使用 $.ajax。
$.get()方法和$.post()有四個參數,前面三個參數和.load()一樣,多了一個第四參數dataType,即伺服器返回的內容格式:包括xml、html、script、json、jsonp 和text。第一個參數為必選參數,後面三個為選擇性參數。
該函數是簡寫的 Ajax 函數,等價於:
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
$.ajax({
type: ‘POST‘,
url: url,
data: data,
success: success,
dataType: dataType
});
--通過直接在url問號緊跟傳參
<!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> <title>Ajax學習</title> <script type="text/javascript" src="jquery-1.11.1.min.js"></script> <script type="text/javascript"> $(function () { $(‘input‘).click(function () { $.get(‘http://localhost:5567/WebForm1.aspx?id=123&UserName=qing&pass=123456‘, function (response, status, xhr) { if (status == "success") { $("#box1").html(response); } }); }); }); </script></head><body> <input type="button" value="Ajax載入資料" /> <div id="box1"></div> </body></html>
WebForm1.aspx.cs檔案:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace WebApplication1{ public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lblMessage.Text = "Hello,Ajax! id:" + Request["id"].ToString() + ",UserName:" + Request["id"].ToString() + ",pass:" + Request["pass"].ToString(); } }}
注意:第四參數dataType是指定非同步返回的類型。一般情況下DataType參數是智能判斷,並不需要我們主動設定,如果主動設定,則會強行按照指定類型格式返回。若本身是純文字,如果強行按照xml或者json資料格式返回的話,那麼就無法擷取資料。
結果:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/2F/0B/wKioL1Oeg5HgWyzHAAFnpMqaNkY097.jpg" title="快照7.jpg" alt="wKioL1Oeg5HgWyzHAAFnpMqaNkY097.jpg" />
等效於:
--通過第二個參數data,對象形式的索引值對傳參
<script type="text/javascript"> $(function () { $(‘input‘).click(function () { $.get(‘http://localhost:5567/WebForm1.aspx‘, {id:123, UserName: ‘qing‘, pass: 123456 }, function (response, status, xhr) { if (status == "success") { $("#box1").html(response); } }); }); });</script>
$.post()方法的使用和$.get()基本上一致,基本都是背後的不同,在使用者使用上體現不出。具體區別如下:
1.GET 請求是通過URL 提交的,而POST 請求則是HTTP 訊息實體提交的;
2.GET 提交有大小限制(2KB),而POST 方式不受限制;
3.GET 方式會被緩衝下來,可能有安全性問題,而POST 沒有這個問題;
--和上面結果相同範例:
<script type="text/javascript"> $(function () { $(‘input‘).click(function () { $.post(‘http://localhost:5567/WebForm1.aspx?id=123‘, {UserName: ‘qing‘, pass: 123456 }, function (response, status, xhr) { if (status == "success") { $("#box1").html(response); } }); }); });</script>
3、$.getScript()和$.getJSON()
$.getScript() 方法通過 HTTP GET 請求載入並執行 JavaScript 檔案。
文法格式:
$.getScript(url,success(response,status))
$.getScript(url,success(response,status))
參數說明:
url:將要請求的 URL 字串。
success(response,status):可選。規定請求成功後執行的回呼函數。額外的參數:response - 包含來自請求的結果資料;status - 包含請求的狀態("success", "notmodified", "error", "timeout" 或 "parsererror")
該函數是簡寫的 Ajax 函數,等價於:
$.ajax({
url: url,
dataType: "script",
success: success
});
$.ajax({
url: url,
data: data,
success: callback,
dataType: json
});
4、$.ajax()方法
$.ajax()是所有ajax 方法中最底層的方法,所有其他方法都是基於$.ajax()方法的封裝。這個方法只有一個參數,傳遞一個各個功能索引值對的對象。
本文出自 “IT技術學習與交流” 部落格,謝絕轉載!