duanpo8329 2013-03-31 03:06
浏览 85
已采纳

通过客户端处理将HTML数据保存到数据库中

I need to save a dynamic table data generated at the client side into the database.

My dynamic table is as follows :

<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">

The twist here is that I am using a radio button in my third column and hence need to pass the checked value on SUBMIT

The javascript code (Reference : Stackoverflow Answer)I am using is :

function savedata() { 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

         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>

So what I need to do is.. Make a key value pair and store it in an array and pass it as an ajax request and insert the same in the database.

Issues :

  1. The checked radio button is not getting stored in the array

  2. I need to create a 2D array and store all the data there and wen I created its showing [object,object]

  3. I need to pass this array using an ajax request into another page and store it in the database.

Please help me how can I do this ?

Thanks in advance. NC

  • 写回答

2条回答 默认 最新

  • dongqi9125 2013-03-31 09:05
    关注

    Here is the solution.. I have modified your code to fix some errors..

    <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 is the file where you will post the json data.

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

    Inside your ajax.php you can write code to save this data to database ot text file whatever you want to do with it. If you print you get the following output.

    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
        )
    )
    

    This is the most ugly way to do it.. It can be done with much less number of line and more efficiently by using only JQuery. I just wanted to show you how it can be done with the code you provided. Let me know if you have any questions.

    Dins

    EDITED...

    Better way to do this

    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'
        });
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题