jQuery表格添加数据并Ajax提交数据

迈不过友情╰ 2023-10-06 23:09 71阅读 0赞

阅读目录

  • 实现效果
    • HTML
    • php

实现效果

在这里插入图片描述
在这里插入图片描述

HTML

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Document</title>
  6. <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
  7. </head>
  8. <body>
  9. <style>
  10. #mform{
  11. margin: 10px; }
  12. #mtable{
  13. border-collapse: collapse; }
  14. #mtable thead th,#mtable thead td{
  15. min-width: 120px; }
  16. #mdiv{
  17. display: none; }
  18. </style>
  19. 姓名:<input type="text" name="name" value="">
  20. 学历:<input type="text" name="education" value="">
  21. 年龄:<input type="text" name="age" value="">
  22. <input id="add" type="button" value="添加"><br>
  23. <form id="mform" action="" method="post">
  24. <table id="mtable" border="1">
  25. <thead>
  26. <tr>
  27. <th>姓名</th>
  28. <th>学历</th>
  29. <th>年龄</th>
  30. </tr>
  31. </thead>
  32. <tbody id="mtbody">
  33. </tbody>
  34. </table>
  35. <div id="mdiv"></div>
  36. <input id="sub" type="button" value="提交"><br>
  37. </form>
  38. <script>
  39. $(function(){
  40. //添加tr
  41. $('#add').click(function(){
  42. var name = $("input[name='name']").val();
  43. var education = $("input[name='education']").val();
  44. var age = $("input[name='age']").val();
  45. var html = '';
  46. html += '<tr>';
  47. html += '<td class="name">'+name+'</td>';
  48. html += '<td class="education">'+education+'</td>';
  49. html += '<td class="age">'+age+'</td>';
  50. html += '</tr>';
  51. $('#mtbody').append(html);
  52. });
  53. //提交
  54. $('#sub').click(function(){
  55. $('#mdiv').html('');
  56. $.each($('#mtbody tr'),function(k){
  57. var name = $('.name', this).text();
  58. var education = $('.education', this).text();
  59. var age = $('.age', this).text();
  60. var html = '';
  61. html += '<input type="text" name="data[' + k + '][name]" value="' + name + '">';
  62. html += '<input type="text" name="data[' + k + '][education]" value="' + education + '">';
  63. html += '<input type="text" name="data[' + k + '][age]" value="' + age + '"><br>';
  64. $('#mdiv').append(html);
  65. });
  66. var data = $("#mform").serialize();
  67. $.ajax({
  68. type: "POST",
  69. data: data,
  70. url: "http://example.com/api/excel_import_export",
  71. dataType: 'json',
  72. success: function (json) {
  73. }
  74. });
  75. });
  76. });
  77. </script>
  78. </body>
  79. </html>

php

  1. <?php
  2. echo '<pre>';
  3. print_r($_POST);
  4. /*
  5. 结果为:
  6. array:2 [
  7. "data" => array:2 [
  8. 0 => array:3 [
  9. "name" => "wgchen"
  10. "education" => "撒"
  11. "age" => "都是"
  12. ]
  13. 1 => array:3 [
  14. "name" => "wgchen阿萨德"
  15. "education" => "撒阿萨德"
  16. "age" => "都是阿萨德"
  17. ]
  18. ]
  19. "s" => "/api/excel_import_export"
  20. ]
  21. */

发表评论

表情:
评论列表 (有 0 条评论,71人围观)

还没有评论,来说两句吧...

相关阅读