0

我正在使用 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?

提前非常感谢!

4

2 回答 2

1

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

索引.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>

保存数据.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); 

?>

希望对你有帮助...

于 2013-08-28T12:21:59.837 回答
0
  1. 'url: "save.json",' 在 ajax 中没有意义,url 应该是在 PHP 中进行发布数据的地方。
  2. 数据:{“数据”:handsontable.getData()},(我不确定handontable.getData()中的格式)......您可能必须在发布之前将其设为json格式的字符串。
  3. 在 php 代码中,尝试 '$stringData = $_POST["data"];' 或尝试使用 json_encode 制作 json 格式的字符串,然后再将其保存到文件中。
于 2013-08-09T13:24:15.557 回答