我正在使用 AJAX 技术创建一个演示。在我的项目中,我使用 AJAX 方法从服务器获取数据。但我收到此错误:
" Uncaught SyntaxError: Unexpected token< xhr.onreadystatechange @main.js"
JS:
(function(){
var xhr = null;
if(window.ActiveXObject){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
xhr = new XMLHttpRequest();
}
xhr.open("GET","data/stuInfo.php",true);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
var HTML = "";
var data = eval("("+xhr.responseText + ")");
for(var i =0;i<data.length;i++){
HTML += "<li><span>"+data[i].Code+"</span>";
HTML += "<span>"+data[i].Name+"</span>";
HTML += "<span>"+data[i].Score+"</span></li>";
}
document.getElementByID("stuInfo").innerHTML = HTML;
}
}
};
})();
PHP:
<?php
header("Content-type:text/json");
$stulist = array(
array("Code" => "10101", "Name" => "刘真真", "Score" => "530"),
array("Code" => "10102", "Name" => "张明基", "Score" => "460"),
array("Code" => "10103", "Name" => "舒虎", "Score" => "660"),
array("Code" => "10104", "Name" => "周小敏", "Score" => "500"),
array("Code" => "10105", "Name" => "陆明明", "Score" => "300")
);
?>
最佳答案
以下是一些需要更改的内容:
- PHP 代码似乎没有对
$stulist
执行任何操作。尝试使用echo
或print
处理 JSON 格式的数据,如下面更新的示例所示。 - 您应该能够使用 JSON.parse(),而不是对响应文本使用
eval()
- 即var data = JSON.parse(xhr.responseText)
,假设内容类型的 header 是“test/json”。请参阅下面的第二个代码片段。 - 对
document.getElementById
的调用在函数名称末尾有一个大写的D
,而不是小写的d
。将其更改为小写d
以避免错误。
PHP:
<?php
header("Content-type:text/json");
$stulist = array(
array("Code" => "10101", "Name" => "刘真真", "Score" => "530"),
array("Code" => "10102", "Name" => "张明基", "Score" => "460"),
array("Code" => "10103", "Name" => "舒虎", "Score" => "660"),
array("Code" => "10104", "Name" => "周小敏", "Score" => "500"),
array("Code" => "10105", "Name" => "陆明明", "Score" => "300")
);
echo json_encode($stulist);
?>
JS:
(function(){
var xhr = null;
if(window.ActiveXObject){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
xhr = new XMLHttpRequest();
}
//sample API request to get sample data in JSON format - replace the second parameter with your endpoint "data/stuInfo.php"
xhr.open("GET","http://elliott.andrewz.org/data/stuInfo.php",true);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
var HTML = "";
//use JSON.parse here instead of eval()
var data = JSON.parse(xhr.responseText);
//reveal what that data object is:
console.log('data: ',data);
for(var i =0;i<data.length;i++){
HTML += "<li><span>"+data[i].Code+"</span>";
HTML += "<span>"+data[i].Name+"</span>";
HTML += "<span>"+data[i].Score+"</span></li>";
}
document.getElementById("stuInfo").innerHTML = HTML;
}
}
};
})();
更新
在评论中,您提到您仍然看到该错误。您是否尝试过使用浏览器控制台的网络选项卡来观察 AJAX 请求以查看响应代码和正文是什么?在下面的屏幕截图中,我正在 Google Chrome 中检查此场景中的 AJAX 请求(可以通过按 F12 或 CTRL+SHIFT 打开该请求+i)。 Mozilla Firefox、Safari 和最新版本的 IE/Edge 都有类似的控制台。我过滤了 XHR 请求,发现 response code是200
。如果您看到不同的数字(例如 400、500),则查找文件或代码时可能出现错误。
关于javascript - 未捕获的语法错误 : Unexpected token< VM3419:1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39940301/