我有一个php文件,其中包含JSON变量,然后将它们编码并在页面中回显它们。然后,我从JS文件中使用AJAX来获取该文件,但是由于某种奇怪的原因,我抛出了一个错误。
我正在使用一个教程来帮助我实现这一目标,但是我尝试在stackoverflow和其他网站上进行查找。
auth.php:
<?php
$userAuth->access = 1;
$userJson = json_encode($userAuth);
echo $userJson;
?>
<script src="auth.js"></script>
auth.js:
const xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
const userAuth = JSON.parse(this.responseText);
console.log(userAuth.access);
}
};
xmlhttp.open("GET", "auth.php", true);
xmlhttp.send();
错误:
VM100:1 Uncaught SyntaxError: Unexpected token A in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.xmlhttp.onreadystatechange (auth.js:4)
xmlhttp.onreadystatechange @ auth.js:4
XMLHttpRequest.send (async)
(anonymous) @ auth.js:10
我的预期结果是控制台1
的日志userAuth.access
,但是我的实际结果却被抛出此错误。
感觉我已经尝试了一切,这可能是服务器出现问题吗?
答案 0 :(得分:0)
我建议将die()
放在echo $userJson;
之后,否则文件底部的script标签也将与JSON一起返回。