我一直在四处寻找我的问题的答案,但我似乎找不到为什么会发生这种情况。
我创建了一个返回 JSON 对象的网络服务器:
http://213.125.101.19/api.php?function=test
之后,我使用以下JavaScript创建了一个HTML文件,以使用Ajax调用JSON。
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxCall(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var response = ajaxRequest.responseText;
obj = JSON.parse(response);
console.log(obj);
if(response.indexOf("Fatal error")>=0){
alert('Error, Try again.');
}else{
document.getElementById("response").value = response;
}
}
}
ajaxRequest.open("GET", "http://213.125.101.19/api.php?function=test", true);
ajaxRequest.send(null);
}
</script>
当我运行此代码时,我的火虫返回
"语法错误:JSON.parse:意外的数据结束obj = JSON.parse(response);"
如果我通过验证器运行我的 JSON,一切似乎都很好。
有什么想法可以解决这个问题吗?
亲切问候卢克
JSON 看起来很简单。我想调用或返回值有问题。
检查status
和responseType
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
console.log('status=' + ajaxRequest.status +
', statusText=' + ajaxRequest.statusText +
', responseType=' + ajaxRequest.responseType +
', responseText=' + ajaxRequest.responseText);
...
}
这个问题的问题是我的HTML请求是从另一台PC发送到我的网络服务器的。
@Olaf Dietsche说,检查ajaxrequest状态是个好主意。这给出了 0,这不是一个成功的响应。
将 html 请求文件复制到 Web 服务器后,问题已解决。
谢谢大家帮助我解决这个问题。