SyntaxError:" JSON.parse:unexpected non-whitespace ..."从PHP返回JSON时 [英] SyntaxError: "JSON.parse: unexpected non-whitespace ..." when returning JSON from PHP
问题描述
我遇到一个问题,从PHP查询返回的JSON无效,我不确定为什么;我还在学习。当排除数据类型
时,以下代码返回:
I'm running into an issue where the JSON returned from a PHP query is not valid and I'm not really sure why; I'm still learning. When the datatype
is excluded the below code returns:
{"Customer_ID":"0", "FirstName":"John", "LastName":"Smith"}
{"Customer_ID":"1", "FirstName":"Jane", "LastName":"Smith"}
否则返回:
SyntaxError: "JSON.parse: unexpected non-whitespace character after ..."
我认为这可能是因为记录没有在单个JSON响应中返回,但由于并发响应是JSON,我无法看到这个问题。有任何想法吗?有什么建议?随意指出语义问题。
I thought this might be because the record is not being returned in a single JSON response, but I can't see that being the issue as the concurrent responses are JSON. Any ideas? Any suggests? Feel free to point out the semantic issues.
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
。尝试这样的事情:
Your JSON is not valid because it consists of multiple objects. What you need to do is put all your results into an array and then echo the json_encode
of that. Try something like this:
$records = array();
if ($result = mysqli_query($conn, $query)) {
while ($records[] = mysqli_fetch_assoc($result)) {
}
}
echo json_encode($records);
这将为您提供如下所示的输出:
This will give you an output that looks something like this:
[
{"Customer_ID":"0", "FirstName":"John", "LastName":"Smith"},
{"Customer_ID":"1", "FirstName":"Jane", "LastName":"Smith"}
]
您可以通过以下方式访问Javascript中的每个元素
and you can access each of the elements in your Javascript by something like
let customer = data[0].FirstName + ' ' + data[0].LastName;
这篇关于SyntaxError:" JSON.parse:unexpected non-whitespace ..."从PHP返回JSON时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!