gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:50:08 25 4
gpt4 key购买 nike

我遇到了一个问题,即从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com