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

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

概述

通過遠端 HTTP POST 請求載入資訊。

這是一個簡單的 POST 請求功能以取代複雜 $.ajax 。請求成功時可呼叫回撥函式。如果需要在出錯時執行函式,請使用 $.ajax。

jQuery 1.12 中 jQuery.post 和 jQuery.get 支援對像參數,這樣一來好處還比較多,比如設定回撥函式的context,或者跨域 post 時可以withCredential: true。用法可以參考示例9。

參數

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

url :發送請求地址。

data :待發送 Key/value 參數。

callback :發送成功時回撥函式。

type :返回內容格式,xml, html, script, json, text, _default。

示例

1描述:

請求 test.php 網頁,忽略返回值:

jQuery 程式碼:

$.post("test.php");

2描述:

請求 test.php 頁面,並一起發送一些額外的資料(同時仍然忽略返回值):

jQuery 程式碼:

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

3描述:

向伺服器傳遞資料陣列(同時仍然忽略返回值):

jQuery 程式碼:

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

4描述:

使用 ajax 請求發送表單資料:

jQuery 程式碼:

$.post("test.php", $("#testform").serialize());

5描述:

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

jQuery 程式碼:

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

6描述:

向頁面 test.php 發送資料,並輸出結果(HTML 或 XML,取決於所返回的內容):

jQuery 程式碼:

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

7描述:

獲得 test.php 頁面的內容,並存儲為 XMLHttpResponse 對象,並通過 process() 這個 JavaScript 函式進行處理:

jQuery 程式碼:

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

8描述:

獲得 test.php 頁面返回的 json 格式的內容::

jQuery 程式碼:

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

9描述:

jQuery 1.12 中 jQuery.post支援對像參數,具體的參數可以參考 $.ajax()

jQuery 程式碼:


          jQuery.post({
            url: 「/example」
          });