返回值:jqXHRjQuery.post(url, [data], [success(data, textStatus, jqXHR)], [dataType])

通过 HTTP POST 方式从服务器载入数据。

这是一个 Ajax 函数的简写形式,它等价于:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

success 回调函数会传入返回的数据,根据响应的 MIME 类型的不同,它可能是一个 XML 根元素、文本字符串、JavaScript 文件或者 JSON 对象。同时还会传入描述响应状态的字符串。

从 jQuery 1.5 开始, success 回调函数还会传入一个 "jqXHR" 对象 (在 jQuery 1.4 中, success 回调函数传入一个 XMLHttpRequest 对象)。

大多数情况下都会指定一个请求成功后的回调函数:

$.post('ajax/test.html', function(data) {
  $('.result').html(data);
});

这个例子会把请求到的 HTML 代码片段插入到页面中。

POST 方式获取的页面永远不会被缓存,所以通过 jQuery.ajaxSetup() 设置的 cacheifModified 选项在这些请求中是无效的。

jqXHR 对象

从 jQuery 1.5 开始,所有 jQuery 的 Ajax 方法都返回一个 XMLHTTPRequest 对象的超集。由 $.post() 方法返回的 jQuery XHR 对象(也可叫做 "jqXHR") 实现了 Promise 接口,使它拥有 Promise 的所有属性,方法和行为。(详见 延迟对象 来获得更多信息)。为了让回调函数的名字统一,便于在 $.ajax() 里使用, jQuery XHR 对象(也可叫做 "jqXHR")同样也提供了 .error(), .success().complete() 方法。这些方法都带有一个参数,该参数是一个函数,此函数在 $.ajax() 请求结束时被调用,并且这个函数接收的参数,与调用 $.ajax() 函数时的参数是一致。

Promise 接口在 jQuery 1.5 里,允许在 $.post() 方法后直接注册 .success(), .complete().error() 回调函数,甚至允许你在请求已经结束后,注册回调函数。如果该请求已经完成,则回调函数会被立刻调用。

// Assign handlers immediately after making the request,
    // and remember the jqxhr object for this request
    var jqxhr = $.post("example.php", function() {
      alert("success");
    })
    .success(function() { alert("second success"); })
    .error(function() { alert("error"); })
    .complete(function() { alert("complete"); });

    // perform other work here ...

    // Set another completion function for the request above
    jqxhr.complete(function(){ alert("second complete"); });

补充说明:

  • 由于浏览器的安全限制,大多数 "Ajax" 请求都服从 同源策略(same origin policy)。即无法从不同的域,子域或协议中正确接收数据。
  • 如果 jQuery.post() 返回一个错误代码,除非在脚本中调用了全局的 .ajaxError() 方法,否则错误将被忽略。或者利用 jQuery 1.5 中 jqXHR 对象的 .error() 方法进行捕获,jqXHR 对象由 jQuery.post() 返回。

示例:

请求 test.php 页面,但忽略返回的结果。

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

示例:

请求 test.php 页面,并传递一些附加的数据,但依然忽略返回的结果。

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

示例:

传递一个数组到服务器,继续忽略返回的结果。

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

示例:

send form data using ajax requests

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

示例:

显示从 test.php 请求到的结果(HTML 或者 XML,根据返回的结果而不同)。

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

示例:

弹出显示从 test.php 请求到的结果,同时传递一些数据(HTML 或者 XML,根据返回的结果而不同)。

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

示例:

获取 test.php 页面的内容,并将内容保存在 XMLHttpResponse 对象中,同时交给 process() 函数做进一步处理。

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

示例:

获取 test.php 页面的内容,其内容是 JSON 格式 (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>)。

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

示例:

使用 ajax 提交表单,并将结果放到一个 div 中。

<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
</head>
<body>

<form action="/" id="searchForm">
   <input type="text" name="s" placeholder="Search..." />
   <input type="submit" value="Search" />
  </form>
  <!-- the result of the search will be rendered inside this div -->
  <div id="result"></div>


<script>


  /* attach a submit handler to the form */
  $("#searchForm").submit(function(event) {

    /* stop form from submitting normally */
    event.preventDefault(); 
        
    /* get some values from elements on the page: */
    var $form = $( this ),
        term = $form.find( 'input[name="s"]' ).val(),
        url = $form.attr( 'action' );

    /* Send the data using post and put the results in a div */
    $.post( url, { s: term },
      function( data ) {
          var content = $( data ).find( '#content' );
          $( "#result" ).empty().append( content );
      }
    );
  });


</script>
</body>
</html>

演示: