我将sql表行传递给一个JavaScript文件,以便在网站页面加载后显示:
php代码:
$sql = "SELECT * FROM `publication_information`";
$pubs = $conn->query($sql);
while ($row = mysqli_fetch_assoc($pubs)) {
$existing_publications[] = $row;
}
$willies = json_encode($existing_publications);
echo $willies;
JavaScript代码:
function WORK(){
var xhr = new XMLHttpRequest();
var url = "/shoba/publications.php";
xhr.onreadystatechange = function() {
// Check if the request is completed and successful
if (xhr.readyState == 4 && xhr.status == 200) {
// Parse the JSON response
var data = JSON.parse(xhr.responseText);
// Do something with the data
console.log(data+" success");
} else {
console.log(error);
}
};
xhr.open("GET", url, true);
xhr.send();
alert("reached function end");
}
在调用函数时,到达了alert,但我得到了uncaught错误:
VM65:1 Uncaught SyntaxError: Unexpected end of JSON input
但我不能发现什么是错误的,据我所知,因为我使用了一个自动功能,它应该工作,但可悲的是它没有。你能告诉我怎么了吗?
1条答案
按热度按时间xdnvmnnf1#
除非保证格式正确,否则建议在解析JSON字符串时使用
try..catch
块。下面的示例给出了问题所在以及导致解析器失败的内容。
我不知道PHP端有什么问题,但是here,我们看到
json_encode
可能返回null
。如果$pubs
没有项目或者null
没有项目,你有没有检查过返回什么JSON字符串?