我正在使用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?
提前多多感谢!
答案 0 :(得分:2)
我有同样的想法,你想做什么。我已经使用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);
?>
希望这会对你有帮助......
答案 1 :(得分:0)