我正在对我网站中包含的 JSON 文件执行 Ajax GET 请求。因此 JSON 文件包含在单独的工作表中。请求的就绪状态为“4”,而状态为“0”。所以请求已发送,但响应文本为空。
我已经验证了 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"}
]
}
最佳答案
你需要创建javaweb项目,然后设置一个tomcat服务器
将所有文件放到javaweb项目中,然后启动tomcat服务器
打开浏览器类型如下:http://localhost:8080/javaweb/test.html
因为xhr.open('GET','json/options_form.json',true);
不能请求本地文件,必须请求服务器文件
关于javascript - Ajax 请求包含 JSON - 就绪状态 4,状态 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56406958/