当前位置:主页 > 查看内容

Ajax提交表单并接收json实例代码

发布时间:2021-04-26 00:00| 位朋友查看

简介:需求: 实现点击按钮后,数据以表单形式提交至服务器,并接收来自服务器的返回数据。过程中页面不刷新。 html代码 html xmlns="http://www.w3.org/1999/xhtml" meta http-equiv="Content-Type" content="text/html; charset=UTF-8" script src="https://cdn.……

需求:

实现点击按钮后,数据以表单形式提交至服务器,并接收来自服务器的返回数据。过程中页面不刷新。

html代码

<html xmlns="http://www.w3.org/1999/xhtml">
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
 <script src="./testajaxjs.js"></script>
 <head>
 </head>
 <body>
  <form id="form1">
   <p>xingming:<input type="text" name="xingming"/></p>
   <p>nianling:<input type="text" name="nianling"/></p>
  </form>
  <button type="button" id="mybt" onclick="mysubmmit()">
   ajax提交
  </button>
 </body>
</html>

js代码

function mysubmmit(){
 $.ajax({
  type: "POST",
  url: "testajaxend.php",
  data: $('#form1').serialize(),
  async: false,
  success: function(databack){
   //console.log("chenggong");
   console.log(databack);
  },
  error: function(request){
   console.log("shibaile");
  }
 });
}

后端php代码

<?php
  $name = $_POST['xingming'];
  $age = $_POST['nianling'];
  $myarray = array("name"=>$name, "age"=>$age);
  $myjson = json_encode($myarray);
  echo $myjson;
?>

以上所述是小编给大家介绍的Ajax提交表单并接收json实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对尊托云数网站的支持!


原文链接:https://m.jb51.net/article/117108.htm
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文


随机推荐