首頁  >  ajax  > $.post(url,[data],[fn],[type])

返回值:XMLHttpRequestjQuery.post(url, [data], [callback], [type])

jQuery $.post() 方法概述

通過遠(yuǎn)程 HTTP POST 請求載入信息。

這是一個簡單的 POST 請求功能以取代復(fù)雜 $.ajax 。請求成功時可調(diào)用回調(diào)函數(shù)。如果需要在出錯時執(zhí)行函數(shù),請使用 $.ajax。

jQuery 1.12 中 jQuery.post 和 jQuery.get 支持對象參數(shù),這樣一來好處還比較多,比如設(shè)置回調(diào)函數(shù)的context,或者跨域 post 時可以withCredential: true。用法可以參考示例9。

參數(shù)

url,[data],[callback],[type]String,Map,Function,StringV1.0

url:發(fā)送請求地址。

data:待發(fā)送 Key/value 參數(shù)。

callback:發(fā)送成功時回調(diào)函數(shù)。

type:返回內(nèi)容格式,xml, html, script, json, text, _default。

示例

1描述:

請求 test.php 網(wǎng)頁,忽略返回值:

jQuery 代碼:
$.post("test.php");

2描述:

請求 test.php 頁面,并一起發(fā)送一些額外的數(shù)據(jù)(同時仍然忽略返回值):

jQuery 代碼:
$.post("test.php", { name: "John", time: "2pm" } );

3描述:

向服務(wù)器傳遞數(shù)據(jù)數(shù)組(同時仍然忽略返回值):

jQuery 代碼:
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });

4描述:

使用 ajax 請求發(fā)送表單數(shù)據(jù):

jQuery 代碼:
$.post("test.php", $("#testform").serialize());

5描述:

輸出來自請求頁面 test.php 的結(jié)果(HTML 或 XML,取決于所返回的內(nèi)容):

jQuery 代碼:
$.post("test.php", function(data){
          alert("Data Loaded: " + data);
          });

6描述:

向頁面 test.php 發(fā)送數(shù)據(jù),并輸出結(jié)果(HTML 或 XML,取決于所返回的內(nèi)容):

jQuery 代碼:
$.post("test.php", { name: "John", time: "2pm" },
          function(data){
          alert("Data Loaded: " + data);
          });

7描述:

獲得 test.php 頁面的內(nèi)容,并存儲為 XMLHttpResponse 對象,并通過 process() 這個 JavaScript 函數(shù)進(jìn)行處理:

jQuery 代碼:
$.post("test.php", { name: "John", time: "2pm" },
          function(data){
          process(data);
          }, "xml");

8描述:

獲得 test.php 頁面返回的 json 格式的內(nèi)容::

jQuery 代碼:
$.post("test.php", { "func": "getNameAndTime" },
          function(data){
          alert(data.name); // John
          console.log(data.time); //  2pm
          }, "json");

9描述:

jQuery 1.12 中 jQuery.post支持對象參數(shù),具體的參數(shù)可以參考 $.ajax()

jQuery 代碼:

          jQuery.post({
            url: “/example”
          });