【问题标题】:save data in editable dynamic html table将数据保存在可编辑的动态 html 表中
【发布时间】:2015-12-07 13:25:28
【问题描述】:

我创建了可编辑的动态 html 表,双击文本用户可以更改它,但更改是临时的,我也希望将其保存在数据库中。

我的表格代码是 (@jsfiddle)

html表格

<table class="editableTable table table-striped table-bordered">
<thead>
    <tr>
        <th> A </th>
        <th> B </th>
        <th> C </th>
        <th> D </th>
    </tr>
</thead>
<tbody>

    <?php
    $sql=" SELECT * from orderid";
    $result = mysqli_query($con, $sql);
    if(mysqli_num_rows($result)>0)
        {
            while($row = mysqli_fetch_assoc($result))
                {?> <tr>
                        <td> <? echo $row['a']; ?> </td>
                        <td> <? echo $row['b']; ?> </td>
                        <td> <? echo $row['c']; ?> </td>
                        <td> <? echo $row['d']; ?> </td>
                    </tr>   
                <?}
        }?>

</tbody>
</table>

脚本代码

 $(function () 
        { 
            $("td").dblclick(function () 
                { 
                    var OriginalContent = $(this).text(); 
                    $(this).addClass("cellEditing"); 
                    $(this).html("<input type='text' value='" + OriginalContent + "' />"); 
                    $(this).children().first().focus(); 
                    $(this).children().first().keypress(function (e) 
                        {
                            if (e.which == 13)
                                {   
                                    var newContent = $(this).val(); 
                                    $(this).parent().text(newContent); 
                                    $(this).parent().removeClass("cellEditing"); 
                                } 
                        }); 
                    $(this).children().first().blur(function()
                        {
                            $(this).parent().text(OriginalContent); 
                            $(this).parent().removeClass("cellEditing"); 
                        }); 
                }); 
        });

我希望用来编辑条目的代码是

$sql1="UPDATE tablename set A='".$a."', B= '".$b."', C= '".$c."', D= '".$d."' WHERE id='".$id."' ";
if(!mysqli_query($con,$sql1))
    {
        die('Error:' . mysqli_error($con));
    }

表格视图

id  A  B  C  D
1   a  b  c  d

谁能告诉我如何在数据库中保存新条目

【问题讨论】:

  • 您可以调用api将数据保存到数据库中
  • 您可以使用 ajax 然后在点击事件时将数据保存在数据库中
  • @Rohit Azad 你能告诉我怎么做吗
  • 添加一个保存按钮,点击后在一个带有更新代码的 php 页面上向您的服务器发出 ajax 发布请求。
  • @lyra 现在是先生。 Thanasis Grammatopoulos 这样做

标签: javascript jquery html mysql ajax


【解决方案1】:

这是一个工作(在客户端)jsfiddle 示例。

我为您解决了一个删除类问题,$(this) 是输入,通过执行 $(this).parent().text("") 然后 $(this) 不存在以再次获取他的父级。

所以你可以像这样打印你的表格

<tr data-id="1"><!-- Include here the row id -->
    <td data-name="a"> a1 </td><!-- Include each cell's name -->
    <td data-name="b"> b1 </td>
    <td data-name="c"> c1 </td>
    <td data-name="d"> d1 </td>
</tr>

我给你加了保存功能

    var saveChanges = function(cell){
        $.ajax({
            type: 'POST',
            url: 'save_changes.php',
            dataType: "json",
            data: getData(cell),
            success: function (json){
                if(json.error){
                    console.log('Error : '+json.error);
                }else{
                    console.log('Data saved.');
                }
            },
            error: function(){
                console.log('Can not connect to the server.');
            }
        });
    }

还有一个获取数据的功能

var getData = function(cell){
    var data = {
        "id" : $.trim(cell.parent().data('id')), // Get row id
        "name" : $.trim(cell.data('name')), // Get the tuple name
        "value" : $.trim(cell.html()) // Get new value
    };
    return data;
}

在服务器上你需要一个 php 文件来保存数据,代码应该是这样的

    // Server Code
    // file "save_changes.php"

    // SQL injection protect
    // http://www.bitrepository.com/sanitize-data-to-prevent-sql-injection-attacks.html
    function sanitize($data){
        // remove whitespaces (not a must though)
        $data = trim($data);

        // apply stripslashes if magic_quotes_gpc is enabled
        if(get_magic_quotes_gpc()){
            $data = stripslashes($data);
        }

        // a mySQL connection is required before using this function
        $data = mysql_real_escape_string($data);

        return $data;
    }

    if(isset($_POST["id"]) && isset($_POST["name"]) && isset($_POST["value"])){
        $id = sanitize($_POST["id"]);
        $name = sanitize($_POST["name"]);
        $value = sanitize($_POST["value"]);
        // Save Data
            // Here you save your data
            $sql1="UPDATE tablename set '".$name."'='".$value."' WHERE id='".$id."' ";
            if(!mysqli_query($con,$sql1)){
                echo '{"error":"'.mysqli_error($con).'"}';
            } else {
                // Report ok
                echo '{"status":"success"}';
            }
    } else {
        echo '{"error":"missing data"}';
    }

注意空格,我添加了一些 $.trim() 来删除它们。 如果新内容与旧内容相同,则不会向服务器发送任何更改,您可能需要禁用它。

$(function() {
  var getData = function(cell) {
    var data = {
      "id": $.trim(cell.parent().data('id')),
      "name": $.trim(cell.data('name')),
      "value": $.trim(cell.html())
    };
    return data;
  }
  var saveChanges = function(cell) {
    $.ajax({
      type: 'POST',
      url: 'save_changes.php',
      dataType: "json",
      data: getData(cell),
      success: function(json) {
        if (json.error) {
          console.log('Error : ' + json.error);
        } else {
          console.log('Data saved.');
        }
      },
      error: function() {
        console.log('Can not connect to the server.');
      }
    });
    /*
        // Server Code
        // file "save_changes.php"
        
        // SQL injection protect
        // http://www.bitrepository.com/sanitize-data-to-prevent-sql-injection-attacks.html
        function sanitize($data){
            // remove whitespaces (not a must though)
            $data = trim($data);

            // apply stripslashes if magic_quotes_gpc is enabled
            if(get_magic_quotes_gpc()){
                $data = stripslashes($data);
            }

            // a mySQL connection is required before using this function
            $data = mysql_real_escape_string($data);

            return $data;
        }

        if(isset($_POST["id"]) && isset($_POST["name"]) && isset($_POST["value"])){
            $id = sanitize($_POST["id"]);
            $name = sanitize($_POST["name"]);
            $value = sanitize($_POST["value"]);
            // Save Data
                // Here you save your data
                $sql1="UPDATE tablename set '".$name."'='".$value."' WHERE id='".$id."' ";
                if(!mysqli_query($con,$sql1)){
                    echo '{"error":"'.mysqli_error($con).'"}';
                } else {
                    // Report ok
                    echo '{"status":"success"}';
                }
        } else {
            echo '{"error":"missing data"}';
        }
    */
  }

  $("#myData td").dblclick(function() {
    var OriginalContent = $.trim($(this).text());
    $(this).addClass("cellEditing");
    $(this).html("<input type='text' value='" + OriginalContent + "' />");
    $(this).children().first().focus();
    $(this).children().first().keypress(function(e) {
      if (e.which == 13) {
        var newContent = $(this).val();
        var cell = $(this).parent();
        cell.text(newContent);
        cell.removeClass("cellEditing");
        if ($.trim(newContent) != OriginalContent)
          saveChanges(cell);
      }
    });
    $(this).children().first().blur(function() {
      var cell = $(this).parent();
      cell.text(OriginalContent);
      cell.removeClass("cellEditing");
    });
  });
});
.editableTable {
  border: solid 1px;
  width: 100%
}
.editableTable td {
  border: solid 1px;
}
.editableTable .cellEditing {
  padding: 0;
}
.editableTable .cellEditing input[type=text] {
  width: 100%;
  border: 0;
  background-color: rgb(255, 253, 210);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myData" class="editableTable table table-striped table-bordered">
  <thead>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
    </tr>
  </thead>
  <tbody>
    <tr data-id="1">
      <!-- Include here the row id -->
      <td data-name="a">a1</td>
      <!-- Include each cell's name -->
      <td data-name="b">b1</td>
      <td data-name="c">c1</td>
      <td data-name="d">d1</td>
    </tr>
    <tr data-id="2">
      <!-- Include here the row id -->
      <td data-name="a">a2</td>
      <!-- Include each cell's name -->
      <td data-name="b">b2</td>
      <td data-name="c">c2</td>
      <td data-name="d">d2</td>
    </tr>
  </tbody>
</table>

【讨论】:

  • 如果允许用户向表中添加/删除行和列,如何保存数据??
  • 由于现在所有的更改都只有一个“UPDATE”查询,所以为了添加一行,我们必须要求服务器创建一个“INSERT”并删除一个行要求“删除”。这些应该是不同的处理程序,并在服务器响应后修改表。比如click add row button > ajax make INSERT > server responds with the id > create row on the table and apply click handlers
【解决方案2】:
$("#save").click(function () {
    var dataA='Data in A td';
    $.ajax({
        type: 'POST',
        url: 'your php page where you do the insert',
        dataType: "json",//response from php page
        data: {
            dataA: dataA//data you will save in database
            },
        success: function (data) {
            alert("Success");
        },
        error: function (data) {
           alert("Error");
        }


    });
});

你可以这样做。只需更改 php 页面的 url,然后您还可以将 dataType 更改为您希望 php 页面响应的任何内容,例如 text 和 html 等等

【讨论】:

  • 我尝试了你的代码,但没有任何反应。还有一个问题我想问一下,在你的代码中,我将如何区分哪一列已被编辑以及在哪一行??
  • 您必须将url part 更改为执行数据库事务的php 页面。如上所述,您可以在拥有remove the class cellEditing 后运行ajax 函数。所以你会知道哪一行正在被编辑。什么都没发生是什么意思。如果你复制并粘贴它什么都不会发生,你需要更改 url 并从那里进行所有数据库事务
  • 我已将 url 链接更改为我在帖子中提供编辑代码的页面,并将代码放在 $(this).parent().removeClass("cellEditing") 之后;什么都没发生,我的意思是我在控制台中没有得到任何响应,也没有出现警告框
猜你喜欢
  • 1970-01-01
  • 2020-04-17
  • 2016-03-24
  • 2011-10-10
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
  • 2013-02-23
  • 2017-02-06
相关资源
最近更新 更多