找回密码
 注册

QQ登录

只需一步,快速开始

查看: 304|回复: 1

jQuery.post()

[复制链接]
发表于 2013-9-12 11:04:13 | 显示全部楼层 |阅读模式
本帖最后由 demo 于 2013-9-13 03:10 编辑

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

Description:
Load data from the server using a HTTP POST request.
This is a shorthand Ajax function, which is equivalent to:
  1. $.ajax({
  2. type: "POST",
  3. url: url,
  4. data: data,
  5. success: success,
  6. dataType: dataType
  7. });
复制代码
The success callback function is passed the returned data, which will be an XML root element or a text string depending on the MIME type of the response. It is also passed the text status of the response.
As of jQuery 1.5, the success callback function is also passed a "jqXHR" object (in jQuery 1.4, it was passed the XMLHttpRequest object).
Most implementations will specify a success handler:
  1. $.post('ajax/test.html', function(data) {
  2. $('.result').html(data);
  3. });
复制代码
This example fetches the requested HTML snippet and inserts it on the page.
Pages fetched with POST are never cached, so the cache and ifModified options in jQuery.ajaxSetup() have no effect on these requests.

The jqXHR ObjectAs of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.
The Promise interface also allows jQuery's Ajax methods, including $.get(), to chain multiple .done(), .fail(), and .always() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.
  1. // Assign handlers immediately after making the request,
  2. // and remember the jqxhr object for this request
  3. var jqxhr = $.post("example.php", function() {
  4. alert("success");
  5. })
  6. .done(function() { alert("second success"); })
  7. .fail(function() { alert("error"); })
  8. .always(function() { alert("finished"); });
  9. // perform other work here ...
  10. // Set another completion function for the request above
  11. jqxhr.always(function(){ alert("second finished"); });
复制代码
Deprecation NoticeThe jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.


Additional Notes:

  • Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
  • If a request with jQuery.post() returns an error code, it will fail silently unless the script has also called the global .ajaxError() method. Alternatively, as of jQuery 1.5, the .error() method of the jqXHR object returned by jQuery.post() is also available for error handling.


Examples:
Example: Request the test.php page, but ignore the return results.
$.post("test.php");



Example: Request the test.php page and send some additional data along (while still ignoring the return results).
1
$.post("test.php", { name: "John", time: "2pm" } );



Example: Pass arrays of data to the server (while still ignoring the return results).
1
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });



Example: Send form data using ajax requests
1
$.post("test.php", $("#testform").serialize());



Example: Alert the results from requesting test.php (HTML or XML, depending on what was returned).

  1. $.post("test.php", function(data) {
  2. alert("Data Loaded: " + data);
  3. });
复制代码
Example: Alert the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned).
  1. $.post("test.php", { name: "John", time: "2pm" })
  2. .done(function(data) {
  3. alert("Data Loaded: " + data);
  4. });
复制代码
Example: Post to the test.php page and get content which has been returned in json format (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>).
  1. $.post("test.php", { "func": "getNameAndTime" },
  2. function(data){
  3. console.log(data.name); // John
  4. console.log(data.time); // 2pm
  5. }, "json");
复制代码
Example: Post a form using ajax and put results in a div
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>jQuery.post demo</title>
  6. <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  7. </head>
  8. <body>
  9. <form action="/" id="searchForm">
  10. <input type="text" name="s" placeholder="Search..." />
  11. <input type="submit" value="Search" />
  12. </form>
  13. <!-- the result of the search will be rendered inside this div -->
  14. <div id="result"></div>
  15. <script>
  16. /* attach a submit handler to the form */
  17. $("#searchForm").submit(function(event) {
  18. /* stop form from submitting normally */
  19. event.preventDefault();
  20. /* get some values from elements on the page: */
  21. var $form = $( this ),
  22. term = $form.find( 'input[name="s"]' ).val(),
  23. url = $form.attr( 'action' );
  24. /* Send the data using post */
  25. var posting = $.post( url, { s: term } );
  26. /* Put the results in a div */
  27. posting.done(function( data ) {
  28. var content = $( data ).find( '#content' );
  29. $( "#result" ).empty().append( content );
  30. });
  31. });
  32. </script>
  33. </body>
  34. </html>
复制代码
 楼主| 发表于 2013-9-13 10:35:26 | 显示全部楼层

jQuery.post() Demo

本帖最后由 demo 于 2013-9-14 02:38 编辑

Let's have this php file on server named ajax_2.php
  1. <?php
  2. $str = 'Response...';
  3. if (isset($_GET['s']) && ($_GET['s']!= '')){
  4.     echo '<p><div id="content">' . $_GET['s'] .
  5.          ' - ' . $_GET['s'] .'</div></p>';
  6. }else{
  7.     echo '<p><div id="content">' . $_POST['s'] . ' + ' . $_POST['s'];
  8.     echo '<b>...</b>' .'</div></p>';
  9. }
  10. ?>
复制代码
Then create another php file to be accessible from clients, file named as ajax_1.php
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>jQuery.post demo</title>
  6. <!-- script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script -->
  7. <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  8. </head>
  9. <body>
  10. <form action="ajax_2.php" id="searchForm" >
  11. <input type="text" name="s" placeholder="Search..." />
  12. <input type="submit" value="Search" />
  13. </form>
  14. ------

  15. <!-- the result of the search will be rendered inside this div -->
  16. <div id="result"></div>
  17. <script>

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

  20.     /* stop form from submitting normally */
  21.     event.preventDefault();
  22.     /* get some values from elements on the page: */
  23.     var $form = $(this),
  24.     term = $form.find('input[name="s"]').val(),
  25.     url = $form.attr('action');
  26.     /* Send the data using post */
  27.     var posting = $.post(url, {s: term});
  28.     /* Put the results in a div */
  29.     posting.done(function(data) {
  30.         var content = $(data).get(0).outerHTML;
  31.         content = '13579' + content;
  32.         $("#result").empty().append(content);
  33.     });
  34.     alert('Res:|' + $("#result").html() + '|');
  35.     $("#result"). append("55555");
  36. });
  37. </script>
  38. </body>
  39. </html>
复制代码
You may active the submition while you click the button.
您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )

GMT-8, 2026-4-11 08:02 , Processed in 0.018381 second(s), 16 queries .

Supported by Weloment Group X3.5

© 2008-2026 Best Deal Online

快速回复 返回顶部 返回列表