我有这个使用 jQuery ajax 调用的 php 代码,它查询数据库并获取结果,然后对结果进行 json 编码
//$rows is another query
foreach($rows as $row) {
$sql = 'SELECT field1, field2 FROM table WHERE field1= :field';
$stmt = $db->prepare($sql);
$stmt->bindValue(':field', trim($row['field_1']));
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($array);
}
输出的 json 看起来像这样
[{"field1":"J1","field2":"0088","field3":"2928868"}][{"field1":"J2","field2":"0171","field3":"2928868"}][{"field1":"J2","field2":"0249","field3":"2928868"}]
我遇到的问题是在 Ajax 响应中处理它。我想做的是遍历每个数组/行并显示数据,但 responseText 显示错误。
我认为它应该看起来像这样,但我不确定。
[{"field1":"J1","field2":"0088","field3":"2928868"},{"field1":"J2","field2":"0171","field3":"2928868"},{"field1":"J2","field2":"0249","field3":"2928868"}]
我的问题是,我是否正确执行 json_encode 以及如何输出每一行?
$.ajax({
type: "POST",
url: "check.php",
data: { order: order },
dataType: "json",
cache: false,
success: function(response) {
if(response.length != 0) {
//output results here
}
else {
$('#foo').text('Order number not found!!');
}
// set the focus to the order input
$('#order').focus().val('');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('An Ajax error was thrown.');
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});