首先,我的MySQL表名为store_items:
id ref store item qty sell
1 2 m1 001 1 12.00
2 2 m1 002 3 12.00
3 3 m3 004 4 5.00
4 3 m3 003 8 10.00从简单的PHP代码开始,将上面的行转换为数组
<?php
$query = "SELECT * FROM store_items ORDER by store Asc";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
//This is for moving PHP array to JS array ? Not sure if it is correct
$js_arr = json_encode($data);
?>现在我一直在寻找一种方法,而不是把它显示为一个表,所以我想把这些结果放在一个类似的Excel中,所以我找到了一个名为:Javascript Handsontable的插件
在放置样式表和脚本之后,继续前进:
<script src="http://localhost/handsontable-master/dist/handsontable.full.js"></script>
<link rel="stylesheet" media="screen" href="http://localhost/handsontable-master/dist/handsontable.full.css">
<link rel="stylesheet" media="screen" href="http://localhost/handsontable-master/demo/css/samples.css">
<link rel="stylesheet" media="screen" href="http://localhost/handsontable-master/demo/css/samples.css">
<link rel="stylesheet" media="screen" href="http://localhost/handsontable-master/demo/css/samples.css">
<style type="text/css">
body {background: white; margin: auto;}
h2 {margin: 20px 0;}
</style>
<div id="example" class="handsontable htColumnHeaders"></div>所以问题就出现在这里:
<script>
var array_code = '<?php echo $js_arr; ?>';
//Alerting result to make sure its correct
alert(array_code);
$(document).ready(function () {
//Not sure how to display the results here ???
var
data =
[
array_code
],
container = document.getElementById('example'),
hot;
hot = new Handsontable(container, {
data: data,
minSpareRows: 1,
colHeaders: true,
contextMenu: true
});
function bindDumpButton() {
Handsontable.Dom.addEvent(document.body, 'click', function (e) {
var element = e.target || e.srcElement;
if (element.nodeName == "BUTTON" && element.name == 'dump') {
var name = element.getAttribute('data-dump');
var instance = element.getAttribute('data-instance');
var hot = window[instance];
console.log('data of ' + name, hot.getData());
}
});
}
bindDumpButton();
});但我无法实现正确的显示;我的目标是这样的:

但是,当var data数组值如下所示时,上面的图片是正确的
var
data = [
['1', '2', 'm1', '001', '1', '12.00'],
['2', '2', 'm1', '002', '3', '12.00'],
['3', '3', 'm3', '004', '4', '5.00'],
],如何正确地将PHP数组值放置在JS数组中?
如有任何建议,将不胜感激。
发布于 2016-11-27 13:42:46
也许我遗漏了什么东西(在这种情况下,评论并编辑我的答案),但我认为您只需要替换:
while ($row = mysql_fetch_assoc($result)){
$data[] = $row;
}通过以下方式:
while ($row = mysql_fetch_row($result)){
$data[] = $row;
}你的“数据”应该是array_code
发布于 2016-11-27 14:44:15
您不需要使用$js_arr = json_encode($data);在HTML表中显示数据,因为它将生成JSON格式的数据,如果不使用JavaScript操作表,则可以避免这样做。只需添加以下HTML代码并对其进行样式设置:
<table>
<thead>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
<th>F</th>
</thead>
<tbody>
<?php if(!empty($data)): ?>
<?php foreach($data as $row): ?>
<tr>
<td><?= $row['id'] ?></td>
<td><?= $row['ref'] ?></td>
<td><?= $row['store'] ?></td>
<td><?= $row['item'] ?></td>
<td><?= $row['qty'] ?></td>
<td><?= $row['sell'] ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>https://stackoverflow.com/questions/40829583
复制相似问题