【问题标题】:Autosave HandsOnTable data to JSON将 HandsOnTable 数据自动保存到 JSON
【发布时间】:2013-08-11 08:26:34
【问题描述】:

我正在使用 HandsOnTable 并尝试实现保存到服务器上的 JSON 文件。

页面是这样的:

<div id="example1" class="handsontable"></div>
<button name="save">Guardar</button>

还有 jQuery:

var handsontable = $container.data('handsontable');

$parent.find('button[name=save]').click(function () {
  $.ajax({
    url: "save.json",
    data: {"data": handsontable.getData()}, //returns all cells' data
    dataType: 'json',
    type: 'POST',
    success: function (res) {
      if (res.result === 'ok') {
        $console.text('Data saved!');
      }
      else {
        $console.text('Save error');
      }
    },
    error: function () {
      $console.text('Save error.');
    }
  });
});

我还在编写一个 PHP 脚本,将上面所有单元格的数据写入 JSON 文件,只要用户单击保存按钮,就应该调用它。现在的样子:

<?php
if(isset($_POST['save'])){

    $myFile = "testFile.json";
    $fh = fopen($myFile, 'w') or die("can't open file");
    $stringData = "Floppy Jalopy\n";
    fwrite($fh, $stringData);
    fclose($fh);
};

?>

我的问题是如何将所有单元格的数据发送到 PHP 变量 $stringData?

提前非常感谢!

【问题讨论】:

    标签: php jquery handsontable


    【解决方案1】:

    我也有你想做的事情。我已经使用 Ajax 和自动完成功能实现了这一点。我将新数据直接放入 load.json 文件中,因此每次按下加载按钮时,用户都会获得新数据。我的代码如下...

    index.html

    <script data-jsfiddle="example">
    var $console = $("#example1console");
            var data = [ [] ];
            var autosaveNotification;
    
                $('#example').handsontable({
                  data: data,
                  minSpareRows: 1,
                  minSpareCols: 1,
                  colHeaders: true,
                  rowHeaders: true, 
                  autoWrapRow: true,
                  currentRowClassName: 'currentRow',
                  currentColClassName: 'currentCol',              
                  contextMenu: { items: {
                                          "row_above": {},
                                          "row_below": {},
                                          "hsep1": "---------",
                                          "col_left": {},
                                          "col_right": {},
                                          "hsep2": "---------",
                                          "remove_row": {},
                                          "remove_col": {}
                                          }
                                },
    
                  afterChange: function (change, source) 
                                {
                                    if (source === 'loadData') {
                                      return; //don't save this change
                                    }
                                    if ($('input[name=autosave]').is(':checked')) 
                                    {
                                      clearTimeout(autosaveNotification);
    
                                        $.ajax({
                                        url: "saveData.php",
                                        dataType: "json",
                                        type: "POST",
                                        data: {"data": handsontable.getData()}, //returns all cells' data
                                        complete: function (data) {
                                              $console.text('Autosaved (' + change.length + ' cell' + (change.length > 1 ? 's' : '') + ')');
                                              autosaveNotification = setTimeout(function () {
                                                $console.text('Changes will be autosaved');
                                              }, 1000);
                                            }
                                      });
                                    }
                               }
                });     
            </script>
    

    saveData.php

    <?php 
    
    $file = 'json\load.json'; 
    
    file_put_contents($file, ""); // Erase file content because we need to use this content for loading.
    
        foreach ($_POST['data'] as $change) 
        {       
            file_put_contents($file, json_encode($change) . ",", FILE_APPEND | LOCK_EX);
        }
    
    // remove last comma from data...
    $fileHandle = fopen($file, 'r+') or die("can't open file");
    $stat = fstat($fileHandle);
    ftruncate($fileHandle, $stat['size']-1);
    fclose($fileHandle);
    
    
    // Append rest of syntax to file content so when press load next time we got ready new data...
    $current = file_get_contents($file);
    $newData = "{ \"data\": [ " . $current . " ] }"; 
    file_put_contents($file, $newData);
    
    // success json response...
    $out = array('result' => 'ok');
    echo json_encode($out); 
    
    ?>
    

    希望对你有所帮助...

    【讨论】:

      【解决方案2】:
      1. 'url: "save.json",'在ajax中没有意义,url应该是PHP中进行发布数据的地方。
      2. data: {"data": handsontable.getData()},(我不确定 handontable.getData() 中的格式)...您可能需要在发布之前将其设为 json 格式的字符串。李>
      3. 在 php 代码中,尝试 '$stringData = $_POST["data"];'或者尝试使用 json_encode 制作 json 格式的字符串,然后再保存到文件中。

      【讨论】:

      • 嗨,我用“escreve.php”替换了“save.json”。 PHP 正在创建一个空的“testFile.json”。因此,脚本正在执行,但来自 handsontable 的数据没有被发送。感谢您的帮助!
      • 嗨,这对我有用:
      猜你喜欢
      • 2017-05-10
      • 2012-11-01
      • 2013-04-24
      • 2014-02-01
      • 2018-05-04
      • 2013-11-29
      • 2015-07-14
      • 2015-07-25
      • 2016-09-19
      相关资源
      最近更新 更多