首页 > 解决方案 > 包含 JSON 的 Ajax 请求 - 就绪状态 4,状态 0

问题描述

我正在对我网站中包含的 JSON 文件执行 Ajax GET 请求。因此 JSON 文件包含在单独的工作表中。请求的就绪状态为“4”,而状态为“0”。所以请求已经发送,但是responsetext是空的。

我已经验证了 JSON 数据。javascript 文件在 HTML5 页面上应返回的位置返回数据。错误处理给出就绪状态“4”和状态“0”。

这是 javascript 文件的代码,JSON 数据是正确的并且经过测试。HTML5 连接也可以正常运行,经过测试。javascript 文件在 HTML 中的正确元素上插入数据。

任何人都可以发现错误吗?谢谢大家!

var xhr = new XMLHttpRequest();                 //create Request Object

xhr.onload = function(){                        //when the Request is loaded, parse it in a responsetext 

if(xhr.status === 200){

    var responseObject = JSON.parse(xhr.responseText);

    var newContent ='';

    for (var i=0; i<responseObject.events.length; i++){

        newContent += responseObject.events[i].color;

        newContent += responseObject.events[i].value;

    }

    document.getElementById("jsonreturn_option").innerHTML = newContent;
}

else{

    document.getElementById("jsonreturn_option").innerHTML = xhr.readyState + "    " + xhr.status  ;

    //readystate is 4, which means that the request has been sent.. 
    //request status is 0, which means that the responsetext is empty.. 
}
};

xhr.open('GET','json/options_form.json',true);
xhr.send(null);                                         //no additional data to be sent

JSON 数据文件

{
"events":[

{  "color": "red", "value": "#f00"},
{  "color": "green", "value": "#0f0"},
{  "color": "blue", "value": "#00f"},
{  "color": "cyan", "value": "#0ff"}
]
}

标签: javascripthtmlajax

解决方案


  1. 您需要创建 javaweb 项目,然后设置一个 tomcat 服务器

  2. 将所有文件放入javaweb项目,然后启动tomcat服务器

  3. 打开浏览器类型,如: http://localhost:8080/javaweb/test.html

因为xhr.open('GET','json/options_form.json',true);不能请求本地文件,必须请求服务器文件


推荐阅读