javascript - 语法错误: "JSON.parse: unexpected non-whitespace ..." when returning JSON from PHP

标签 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);

    }

?>

最佳答案

您的 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;

关于javascript - 语法错误: "JSON.parse: unexpected non-whitespace ..." when returning JSON from PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54738536/

相关文章:

javascript - 位置 :absolute div inside another position:absolute div and making them position:fixed

php - 如何将不带换行符的字符串连接到 MySQL 中?

javascript - 如何在 PHP 中获取 [object Object] 的内容?

javascript - jQuery 多层 JSON

javascript - 如何在 JavaScript 中访问 "browsing context"?

javascript - 使用 JavaScript 将 _target ="blank"动态更改为 _target ="self"

javascript - 通过另一个值元素查找元素 ID

php - 用下划线将句子中的否定句与后面的词联系起来

php - zend db 像通配符一样选择

javascript - 固定位置窗口滚动问题