温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

jQuery.post使用的注意事项有哪些

发布时间:2022-03-05 10:43:56 来源:亿速云 阅读:142 作者:iii 栏目:web开发

本篇内容介绍了“jQuery.post使用的注意事项有哪些”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

  由于浏览器的安全限制,大多数“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="https://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>

“jQuery.post使用的注意事项有哪些”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI