【发布时间】:2017-04-08 12:08:51
【问题描述】:
我的index.php 中有一个 AJAX 请求到另一个文件 (get_code.php),该文件查询数据库并将 json_encoded 数组返回到 index.php,在那里它被转换为带有 @987654325 的字符串@。
这很好用,但事实上它会像这样出现在页面上:
[{"code":"GG500","desc":"Desc 1","price1":"9.35","price2":"8.25","price3":"7.75","avg":"7.994198","lwcm":"7.9568","cost":"4.63"},
{"code":"GGC4","desc":"Desc 2","price1":"","price2":"","price3":"","avg":"504.666666","lwcm":"387.5","cost":"260.61"}]
问题:
如何获取此字符串并将其转换为普通数组或我可以在index.php 的 HTML 表格中显示的任何内容?
当前代码:
index.php jQuery
if (!data.result) {
$('#modal2').modal('show');
$('.msgs').text(data.error);
$('#cdnf').text(data.code);
$('#tarray').text(JSON.stringify(data.tarray));
}
index.php HTML
<p id="tarray"></p><!-- needs to be a table -->
get_code.php PHP
$taq = mysql_query("SELECT * FROM variants")or die(mysql_error());
if($taq){
$tarray = array();
while($row = mysql_fetch_assoc($taq)){
$tarray[] = array(
'code' => $row['va_code'],
'desc' => $row['va_description'],
'price1' => $row['price_1'],
'price2' => $row['price_2'],
'price3' => $row['price_3'],
'avg' => $row['average_price'],
'lwcm' => $row['lwcm'],
'cost' => $row['cost']
);
}
};
die(json_encode(['tarray' => $tarray]));
【问题讨论】:
-
你需要迭代 json 对象。读取对象,然后打印值
-
JSON.parse 用于将 json 解码为数组,JSON.stringify 用于将数组编码为 json
-
好的,谢谢@Tushar - 我如何在 jQuery 中解决这个问题?
-
@hassan JSON.parse 返回错误
Unexpected token o in JSON at position 1? -
取决于您希望如何显示数据。 ;) 您可以创建一个表并填充每一行,也可以直接转储数据。这一切都取决于要求