jquery ajax使用php json编码获取数据库结果

时间:2014-01-31 15:53:31

标签: php jquery ajax json responsetext

我有这个PHP代码,使用jQuery ajax调用数据库并获取结果,然后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);
    }
});

1 个答案:

答案 0 :(得分: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) {

    }

相关问题/进一步阅读:How to parse JSON in JavaScript