【问题标题】:Save HTML data into database by client side processing通过客户端处理将 HTML 数据保存到数据库中
【发布时间】:2013-05-08 19:22:25
【问题描述】:

我需要将客户端生成的动态表数据保存到数据库中。

我的动态表如下:

<table class="table" id = "myTable">
      <thead>
          <tr>
            <th>Roll No</th>
            <th>Student Name</th>
            <th>Attendance</th>
          </tr>
      </thead>
      <tbody>
          <?php foreach($results as $students) {?>
          <tr id="<?= $students->roll_no;?>" align ="center">
            <td><?= $students->roll_no;?></td>
            <td><?= $students->full_name;?></td>
            <td><input type="radio" id="att" name="attendance" value="present">Present
<input type="radio" id="att" name="attendance" value="absent">Absent</td>
          </tr>
          <?php } ?>                                                        
      </tbody>
    </table>
    <input type="submit" onClick="savedata()" name="submit" value="SAVE">

这里的转折是我在第三列中使用了一个单选按钮,因此需要在 SUBMIT 上传递选中的值

我使用的javascript代码(参考:Stackoverflow Answer)是:

函数保存数据() { var oTable = document.getElementById('myTable'); //获取表格

      var rowLength = oTable.rows.length;
      //gets rows of table

      for (i = 1; i < rowLength; i++){
      //loops through rows

         var oCells = oTable.rows.item(i).cells;
         //gets cells of current row
         var cellLength = oCells.length;
             for(var j = 0; j < cellLength; j++){
             //loops through each cell in current row
                <!--get your cell info here-->
                if(j == cellLength-1)
                {
                      var cellVal = $('input[name="attendance"]:radio:checked');
                      alert(cellVal);
                                        // store it in array here
                                       radioarr = [oTable.rows.item(i).cells,oCells.item(j).innerHTML]; 
                }
                else
                {
                      var cellVal = oCells.item(j).innerHTML;
                      alert(cellVal);
                                        // store it in array here 
                                       fieldarr = [oTable.rows.item(i).cells,oCells.item(j).innerHTML];
                }
             }

      }
  }
  $.ajax{

      // Pass the data to another page insert.php and store it in the database
  }
</script>

所以我需要做的是.. 制作一个键值对并将其存储在一个数组中并将其作为 ajax 请求传递并将其插入数据库中。

问题:

  1. 选中的单选按钮未存储在数组中

  2. 我需要创建一个二维数组并将所有数据存储在那里,然后我创建了它的显示 [object,object]

  3. 我需要使用 ajax 请求将此数组传递到另一个页面并将其存储在数据库中。

请帮帮我,我该怎么做?

提前致谢。数控

【问题讨论】:

  • 如果您知道需要采取的步骤,能否向我们展示您为采取这些步骤而编写的代码?您在这些步骤中遇到了哪些问题?
  • 您将需要使用 jQuery 的 ajax()post() 方法。如果没有提供关于 AJAX 的完整教程,如果没有看到您尝试使用 AJAX 失败的示例代码,将很难提供更多指针。
  • @John:我已经在编辑中解释了这些问题
  • 我建议创建您从表中获取的数据的 json 对象,并对您执行 json_decode .. 的 php 文件进行 ajax 查询
  • 在您的表格中,您可以通过为表格中的所有单选按钮赋予相同的名称属性值来创建单选按钮组。所以表中的所有单选按钮都在同一组中。如果不是故意的,您应该为每一行使用不同的名称,例如出席_01、出席_02 等等。

标签: php javascript ajax jquery client-side


【解决方案1】:

这是解决方案..我已经修改了您的代码以修复一些错误..

<table class="table" id = "myTable">
  <thead>
      <tr>
        <th>Roll No</th>
        <th>Student Name</th>
        <th>Attendance</th>
      </tr>
  </thead>
  <tbody>
      <?php foreach($results as $students) {?>
      <tr id="<?= $students["roll_no"];?>" align ="center">
        <td id="roll_no"><?= $students["roll_no"];?></td>
        <td id="full_name"><?= $students["full_name"];?></td>

         <!-- Attendance has to be unique for each row -->
        <td id="attendance"><input type="radio" id="att" name="attendance_<?= $students["roll_no"] ?>" value="present">Present
            <input type="radio" id="att" name="attendance_<?= $students["roll_no"]?>" value="absent">Absent</td>
      </tr>
      <?php } ?>                                                        
  </tbody>
</table>

  <script>

    function savedata() { 
        var roll_no = "";
        var jsonObject = '[';
        var oTable = document.getElementById('myTable');
    //gets table

    var rowLength = oTable.rows.length;
    //gets rows of table

    for (i = 1; i < rowLength; i++){
    //loops through rows
        jsonObject += "{";
       var oCells = oTable.rows.item(i).cells;
       //gets cells of current row
       var cellLength = oCells.length;
           for(var j = 0; j < cellLength; j++){

           //loops through each cell in current row
              <!--get your cell info here-->
              //added cell name so that I can create json id
              var cellName = oCells.item(j).id;
              var cellVal = oCells.item(j).innerHTML;

              if(j==0)
                  roll_no = cellVal;
              if(cellVal.search('radio')>0){
                  var cellVal = $('input[name="attendance_'+roll_no+'"]:radio:checked').val();
              }
              // A dirty way to creat json
              jsonObject += '"' +cellName + '":"' + cellVal + '",';

           }
           jsonObject = jsonObject.slice(0,jsonObject.length-1);
           jsonObject += '},';
        }
        jsonObject = jsonObject.slice(0,jsonObject.length-1);
        jsonObject += ']';

       // the json looks like this for 3 rows depending on what radio button u select
       // [{"roll_no":"10","full_name":"Name 1","attendance":"present"},{"roll_no":"14","full_name":"Name 2","attendance":"absent"},{"roll_no":"18","full_name":"Name 3","attendance":"present"}]

        //send this data to a php page
        $.ajax({
            type: "POST",
            url: "ajax.php",
            data:"json=" + jsonObject,
            processData: false, 
            dataType: 'json'
        });

      }
</script>

ajax.php 是您将在其中发布 json 数据的文件。

<?php

    $value = json_decode(stripslashes($_POST["json"])); 
    print_r($value);
?>

在您的 ajax.php 中,您可以编写代码将这些数据保存到数据库或文本文件中,无论您想对它做什么。如果你打印,你会得到以下输出。

Array
(
[0] => stdClass Object
    (
        [roll_no] => 10
        [full_name] => Name 1
        [attendance] => present
    )

[1] => stdClass Object
    (
        [roll_no] => 14
        [full_name] => Name 2
        [attendance] => absent
    )

[2] => stdClass Object
    (
        [roll_no] => 18
        [full_name] => Name 3
        [attendance] => present
    )
)

这是最丑陋的方法。仅使用 JQuery 就可以用更少的行数更有效地完成它。我只是想向您展示如何使用您提供的代码来完成它。如果您有任何问题,请告诉我。

丁丁

已编辑...

更好的方法

function savedata1() { 

var obj = $('#myTable tbody tr').map(function() {
    var $row = $(this);
    var roll = $row.find(':nth-child(1)').text();
    var atd = $row.find('td input[name="attendance_'+roll+'"]:radio:checked').val()
    return {
        roll_no: $row.find(':nth-child(1)').text(),
        full_name: $row.find(':nth-child(2)').text(),
        attendance: atd
    };
}).get();

 $.ajax({
        type: "POST",
        url: "ajax.php",
        data:"json=" + JSON.stringify(obj),
        processData: false, 
        dataType: 'json'
    });

}

【讨论】:

  • 哦,非常感谢你的代码。你能告诉我一个更好的方法吗?我只是找不到更好的方法,所以不得不这样做……:)
【解决方案2】:

你不需要在 PHP 文件中解码 json 只需使用

 $value = stripslashes($_POST["json"]); 

【讨论】:

    猜你喜欢
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 2014-02-17
    • 2018-02-02
    • 1970-01-01
    相关资源
    最近更新 更多