請求 test.php 網頁,忽略返回值:html
$.post("test.php");
經過 AJAX POST 請求改變 div 元素的文本:jquery
$("input").keyup(function(){ txt=$("input").val(); $.post("demo_ajax_gethint.asp",{suggest:txt},function(result){ $("span").html(result); }); });
親自試一試ajax
post() 方法經過 HTTP POST 請求從服務器載入數據。json
jQuery.post(url,data,success(data, textStatus, jqXHR),dataType)
參數 | 描述 |
---|---|
url | 必需。規定把請求發送到哪一個 URL。 |
data | 可選。映射或字符串值。規定連同請求發送到服務器的數據。 |
success(data, textStatus, jqXHR) | 可選。請求成功時執行的回調函數。 |
dataType | 可選。規定預期的服務器響應的數據類型。數組 默認執行智能判斷(xml、json、script 或 html)。瀏覽器 |
該函數是簡寫的 Ajax 函數,等價於:緩存
$.ajax({ type: 'POST', url: url, data: data, success: success, dataType: dataType});
根據響應的不一樣的 MIME 類型,傳遞給 success 回調函數的返回數據也有所不一樣,這些數據能夠是 XML 根元素、文本字符串、JavaScript 文件或者 JSON 對象。也可向 success 回調函數傳遞響應的文本狀態。安全
對於 jQuery 1.5,也能夠向 success 回調函數傳遞 jqXHR 對象(jQuery 1.4 中傳遞的是 XMLHttpRequest 對象)。服務器
大部分實現會規定一個 success 函數:
$.post("ajax/test.html", function(data) { $(".result").html(data); });
本例讀取被請求的 HTML 片斷,並插入頁面中。
經過 POST 讀取的頁面不被緩存,所以 jQuery.ajaxSetup() 中的 cache 和 ifModified 選項不會影響這些請求。
註釋:因爲瀏覽器安全方面的限制,大多數 "Ajax" 請求遵照同源策略;請求沒法從不一樣的域、子域或協議成功地取回數據。
註釋:若是由 jQuery.post() 發起的請求返回錯誤代碼,那麼不會有任何提示,除非腳本已調用了全局的 .ajaxError() 方法。或者對於 jQuery 1.5,jQuery.post() 返回的 jqXHR 對象的 .error() 方法也能夠用於錯誤處理。
對於 jQuery 1.5,全部 jQuery 的 AJAX 方法返回的是 XMLHTTPRequest 對象的超集。由 $.post() 返回的 jQuery XHR 對象或 "jqXHR,"實現了約定的接口,賦予其全部的屬性、方法,以及約定的行爲。出於對由 $.ajax() 使用的回調函數名稱便利性和一致性的考慮,它提供了 .error(), .success() 以及 .complete() 方法。這些方法使用請求終止時調用的函數參數,該函數接受與對應命名的 $.ajax() 回調函數相同的參數。
jQuery 1.5 中的約定接口一樣容許 jQuery 的 Ajax 方法,包括 $.post(),來連接同一請求的多個 .success()、.complete() 以及 .error() 回調函數,甚至會在請求也許已經完成後分配這些回調函數。
// 請求生成後當即分配處理程序,請記住該請求針對 jqxhr 對象 var jqxhr = $.post("example.php", function() { alert("success"); }) .success(function() { alert("second success"); }) .error(function() { alert("error"); }) .complete(function() { alert("complete"); }); // 在這裏執行其餘任務 // 爲上面的請求設置另外一個完成函數 jqxhr.complete(function(){ alert("second complete"); });
請求 test.php 頁面,並一塊兒發送一些額外的數據(同時仍然忽略返回值):
$.post("test.php", { name: "John", time: "2pm" } );
向服務器傳遞數據數組(同時仍然忽略返回值):
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
使用 ajax 請求發送表單數據:
$.post("test.php", $("#testform").serialize());
輸出來自請求頁面 test.php 的結果(HTML 或 XML,取決於所返回的內容):
$.post("test.php", function(data){ alert("Data Loaded: " + data); });
向頁面 test.php 發送數據,並輸出結果(HTML 或 XML,取決於所返回的內容):
$.post("test.php", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); });
得到 test.php 頁面的內容,並存儲爲 XMLHttpResponse 對象,並經過 process() 這個 JavaScript 函數進行處理:
$.post("test.php", { name: "John", time: "2pm" }, function(data){ process(data); }, "xml");
得到 test.php 頁面返回的 json 格式的內容:
$.post("test.php", { "func": "getNameAndTime" }, function(data){ alert(data.name); // John console.log(data.time); // 2pm }, "json");