从PHP返回JSON时,SyntaxError:“ JSON.parse:意外的非空白...”

时间:2019-02-17 23:09:29

标签: javascript php html json mysqli

我遇到了一个问题,即从PHP查询返回的JSON无效,我不确定为什么。我还在学习。当排除datatype时,以下代码返回:

{"Customer_ID":"0", "FirstName":"John", "LastName":"Smith"}
{"Customer_ID":"1", "FirstName":"Jane", "LastName":"Smith"}

否则它将返回:

SyntaxError: "JSON.parse: unexpected non-whitespace character after ..."

我认为这可能是因为未在单个JSON响应中返回记录,但是由于并发响应是JSON,因此我看不出是问题所在。有任何想法吗?有什么建议吗?随时指出语义问题。

  

HTML:

getRecord("*", "customer", "");
  

JavaScript:

function getRecord(field, table, condition) {
    var request = $.ajax({
        url: "./handler.php",
        method: "GET",
        dataType: "JSON",
        cache: "false",
        data: {
            action: "SELECT",
            field: `${field}`,
            table: `${table}`,
            condition: `${condition}`,
        },
    });

    request.done(function(data, status, xhr) {
        console.log(data, status, xhr);
    });

    request.fail(function(xhr, status, error) {
        console.log(xhr, status, error);
    });

};
  

PHP:

<?php

    # IMPORT SETTINGS.
    include "settings.php";

    # FUNCTION DISPATCHER.
    switch($_REQUEST["action"]) {

        case "SELECT":
            getRecord($conn);
            break;

        default:
            printf('Connection Error: Access Denied.');
            mysqli_close($conn);
    }

    # LIST OF COLUMNS THAT WE NEED.

    function getRecord($conn) {
        $table = $_REQUEST["table"];
        $field = $_REQUEST["field"];
        $condition = $_REQUEST["condition"];

        if (!empty($condition)) {
            $query = "SELECT $field FROM $table WHERE $condition";
        } else {
            $query = "SELECT $field FROM $table";
        }

        if ($result = mysqli_query($conn, $query)) {
            while ($record = mysqli_fetch_assoc($result)) {
                echo json_encode($record);
            }
        }

        # CLOSE THE CONNECTION.
        mysqli_close($conn);

    }

?>

1 个答案:

答案 0 :(得分:5)

您的JSON无效,因为它包含多个对象。您需要做的是将所有结果放入数组,然后回显该数组的json_encode。尝试这样的事情:

    $records = array();
    if ($result = mysqli_query($conn, $query)) {
        while ($records[] = mysqli_fetch_assoc($result)) {
        }
    }
    echo json_encode($records);

这将为您提供类似于以下内容的输出:

[
    {"Customer_ID":"0", "FirstName":"John", "LastName":"Smith"},
    {"Customer_ID":"1", "FirstName":"Jane", "LastName":"Smith"}
]

,您可以通过类似的方式访问Javascript中的每个元素

let customer = data[0].FirstName + ' ' + data[0].LastName;