下面的示例展示了如何使用 $.ajax 和 Handsontable 加载和保存数据:
var first = true;
$("#example6grid").handsontable({
rows: 8,
cols: 8,
rowHeaders: true,
colHeaders: true,
minSpareCols: 1,
minSpareRows: 1,
contextMenu: true,
onChange: function (change) {
if (first) {
first = false;
return; //don't save this change
}
$.ajax({ //saves changes from Handsontable
url: "save.php",
dataType: "json",
type: "POST",
data: {"data": $("#example6grid").handsontable('getData')}, //returns full array of grid data
//data: change, //contains only information about changed cells
success: function (data) {
console.log("saved", data);
},
error: function (data) {
console.log("error", data);
}
});
}
});
$.ajax({ //loads data to Handsontable
url: 'source.json',
dataType: 'json',
type: 'GET',
success: function(res){
$("#example6grid").handsontable("loadData", res.data);
}
});
上面的代码假定<div id="example6grid" class="dataTable"></div>存在,并且该文件source.json包含以下 JSON:
{
"data": [
["", "Kia", "Nissan", "Toyota", "Honda"],
["2008", 10, 11, 12, 13],
["2009", 20, 11, 14, 13],
["2010", 30, 15, 12, 13]
]
}