返回介绍

jQuery.post()

发布于 2017-09-11 17:02:29 字数 6327 浏览 1212 评论 0 收藏 0

所属分类:Ajax > 快捷方法

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

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

  • 添加的版本: 1.0jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

    • url 类型: String 一个包含发送请求的URL字符串
    • data 类型: PlainObject, String 发送给服务器的字符串或Key/value键值对。
    • success(data, textStatus, jqXHR) 类型: Function() 当请求成功后执行的回调函数。
    • dataType 类型: String 从服务器返回的预期的数据类型。默认:智能判断(xml, json, script, or html)。

这是一个 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对象的超集。这个通过$.get()方法返回的jQuery XHR对象,或“jqXHR,”实现了 Promise 接口,使它拥有 Promise 的所有属性,方法和行为(见Deferred object获取更多信息)。jqXHR.done() (表示成功), jqXHR.fail() (表示错误), 和 jqXHR.always() (表示完成, 无论是成功或错误) 方法接受一个函数参数,用来请求终止时被调用。关于这个函数接收参数的详细信息,请参阅 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中不赞成使用,已经过时。他们最终将被取消(移除),你的代码应该为次做好准备,使用 jqXHR.done(), jqXHR.fail(), 和 jqXHR.always() 代替.

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

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

例子:

Example: 请求 test.php 页面, 但是忽略返回结果

$.post("test.php");

Example: 请求 test.php 页面 并且发送url参数(虽然仍然忽视返回的结果)。

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

Example: 传递数组形式data参数给服务器 (虽然仍然忽视返回的结果)。

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

Example: 使用Ajax请求发送表单数据。

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

Example: Alert 从 test.php请求的数据结果 (HTML 或者 XML,取决于返回的结果)。

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

Example: Alert 从 test.cgi请求并且发送url参数的数据结果 (HTML 或者 XML,取决于返回的结果)。

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

Example: 得到test.php的内容,存储在一个 XMLHttpResponse 对象中并且运用 process() JavaScript函数。

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

Example: Posts to the test.php page and gets contents which has been returned in json format (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>).

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文