Javascript JSON.parse:JSON 数据第 1 行第 1 列的意外字符 (php)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42341547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON.parse: unexpected character at line 1 column 1 of the JSON data (php)
提问by AshrafNmd
I am unable to access json data as it always fails and gives error as SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data search.php outputs the json data but scripts.js outputs json.parse error script.js
我无法访问 json 数据,因为它总是失败并给出错误为 SyntaxError: JSON.parse: JSON 数据 search.php 的第 1 行第 1 列的意外字符输出 json 数据,但 scripts.js 输出 json.parse 错误 脚本。 js
// execute when the DOM is fully loaded
$(function() {
console.log("1");
$("#q").typeahead({
autoselect: true,
highlight: true,
minLength: 1
},
{
source: search,
templates: {
empty: "no places found yet",
suggestion: _.template("<p><%- subname %></p>")
}
});
// re-center map after place is selected from drop-down
$("#q").on("typeahead:selected", function(eventObject, suggestion, name) {
});
});
function search(query, cb)
{
// get places matching query (asynchronously)
var parameters = {
sub: query
};
$.getJSON("search.php", parameters)
.done(function(data, textStatus, jqXHR) {
cb(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown.toString());
});
}
search.php
搜索.php
<?php
require(__DIR__ . "/../includes/config.php");
$subjects = [];
$sub = $_GET["sub"]."%";
$sql = "SELECT * from subjects where subname LIKE '$sub'";
echo $sql;
if($rows = mysqli_query($con,$sql))
{
$row = mysqli_fetch_array($rows);
while($row){
$subjects[] = [
'subcode' =>$row["subcode"],
'subname' => $row["subname"],
'reg' => $row["reg"],
'courseid' =>$row["courseid"],
'branchid' => $row["branchid"],
'yrsem' => $row["yrsem"]
];
$row = mysqli_fetch_array($rows);
}
}
// output places as JSON (pretty-printed for debugging convenience)
header("Content-type: application/json");
print(json_encode($subjects, JSON_PRETTY_PRINT));
?>
回答by Anand Deep Singh
Solution for your problem is JSON.stringify
您的问题的解决方案是JSON.stringify
You need to convert your data output into stringi.e.,
您需要将数据输出转换为字符串,即,
var yourDataStr = JSON.stringify(yourdata)
and then validate your data with
然后验证您的数据
JSON.parse(yourDataStr)
Then you can get your result. To validate, you can pass your data in below function :-
然后你可以得到你的结果。要验证,您可以在以下函数中传递您的数据:-
function validateJSON(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}

