2

我有这个使用 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);
    }
});
4

1 回答 1

4

您应该对整个输出进行 JSON 编码,而不是输出每行的 json 编码版本:

$output = array();

//$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);

    $output[] = $array;
}

echo json_encode($output);

回答您的问题,要在 JavaScript 中使用您的 JSON,您将其视为对象数组。您甚至可以使用 jQuery 通过$.each帮助您遍历结果:

    if(response.length != 0) {

          $.each(response, function(index, row) {

              console.log(row);
              // Access your row variables like so:
              // row.field1, row.field2, row.field3, etc.
          }

    }

如果您更喜欢本机循环,您可以执行以下操作:

    // Let i start at zero. If the response array length is less than i, execute the block, then increment i by 1.
    for(var i = 0; response.length < i; i += 1) {

    }

相关问题/进一步阅读:如何在 JavaScript 中解析 JSON

于 2014-01-31T15:55:58.933 回答