加载中...

jQuery.post()


概述    jQuery.post( url [, data ] [, success ] [, dataType ] )

返回值:XMLHttpRequest

描述:使用一个HTTP POST 请求从服务器加载数据。

  • V : 1.0jQuery.post( url [, data ] [, success ] [, dataType ] )

    • url
      类型:String
      一个包含发送请求的URL字符串.
    • data
      类型:PlainObject or String
      一个普通对象或字符串,通过请求发送给服务器。
    • success
      类型:Function( PlainObject data, String textStatus, jqXHR jqXHR )
      当请求成功后执行的回调函数。 如果提供dataType选项,那么这个success选项是必须的, 但这种情况下你可以使用null
    • dataType
      类型:String
      从服务器返回的预期的数据类型。默认:智能猜测(xml, json, script, text,html)。
  • V : 1.12/2.2jQuery.post( [settings ] )

    • settings
      类型:PlainObject
      一组用于配置Ajax请求的键/值对。除了url以外的所有选项属性都是可选的。任何默认选项可以用$.ajaxSetup()进行设置。所有选项设置的完整列表,请参阅jQuery.ajax( settings )。 type(类型)选项将自动设置为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中 ,它传递的是XMLHttpRequest对象)。

大多数实现将指定一个成功的处理函数:

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

这个示例所请求的全部HTML代码片段插入到页面中。

POST 获取的页面是从来不会被缓存, 所以这些请求中的 cacheifModified 选项在 jQuery.ajaxSetup() 是无效的。

The jqXHR Object(jqXHR 对象)

从jQuery 1.5开始,所有jQuery的Ajax方法都返回一个XMLHTTPRequest对象的超集。这个通过$.post()方法返回的jQuery XHR对象,或“jqXHR”,实现了 Promise 接口,使它拥有 Promise 的所有属性,方法和行为。jqXHR.done() (表示成功), jqXHR.fail() (表示错误), 和 jqXHR.always() (表示完成, 无论是成功或错误;在jQuery 1.6 中添加) 方法接受一个函数参数,用来请求终止时被调用。关于这个函数接收参数的详细信息,请参阅 jqXHR Object 文档中的 $.ajax() 章节。

Promise 接口也允许jQuery的Ajax方法, 包括 $.get(), 在一个单独的请求中关联到 .done(), .fail(), 和 .always() 回调函数, 甚至允许你在请求已经结束后,指派回调函数。如果该请求已经完成,则回调函数会被立刻调用。

// 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"); });

Deprecation Notice(推荐使用的注意事项:)

jqXHR.success(), jqXHR.error(), 和 jqXHR.complete() 回调方法 在jQuery 1.5中引进, 在jQuery 1.8中不赞成使用,已经过时。他们最终将被取消(移除),你的代码应该为次做好准备, 从jQuery 3.0开始被删除,你可以使用 jqXHR.done(), jqXHR.fail(), 和 jqXHR.always() 代替.

Additional Notes:(其他注意事项:)

  • 由于浏览器的安全限制,大多数“Ajax”的要求,均采用同一起源的政策 ;即无法从不同的域,子域或协议中正确接收数据。
  • 如果一个jQuery.post()请求返回一个错误代码,它会静静的失败,除非脚本调用全局的.ajaxError()方法。在jQuery 1.5, 通过jQuery.post()返回的jqXHR对象的.error()方法也可用于错误处理。

示例

实例

请求 test.php 网页,忽略返回值:

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

实例

请求 test.php 页面,并一起发送一些额外的数据(同时仍然忽略返回值):

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

实例

向服务器传递数据数组(同时仍然忽略返回值):

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

实例

使用 ajax 请求发送表单数据:

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() 这个 JavaScript 函数进行处理:

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

实例

获得 test.php 页面返回的 json 格式的内容::

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

实例

jQuery 1.12 中 jQuery.post支持对象参数,具体的参数可以参考 $.ajax()

jQuery 代码:
 jQuery.post({
      url: "/example" }); 

实例

用ajax传递一个表单并把结果在一个div中

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.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>

运行一下


还没有评论.