javascript - 包含 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"}
]
}
解决方案
您需要创建 javaweb 项目,然后设置一个 tomcat 服务器
将所有文件放入javaweb项目,然后启动tomcat服务器
打开浏览器类型,如: http://localhost:8080/javaweb/test.html
因为xhr.open('GET','json/options_form.json',true);
不能请求本地文件,必须请求服务器文件
推荐阅读
- regex - 如何在两个单词之间包含可选空格而不选择下一个单词?
- android - 在 Gradle 中编写依赖项的各种方式有什么区别?
- c - 如何在 C 中创建自定义多个进程?
- ruby-on-rails - 将模型嵌套到另一个嵌套模型中,保存时要求第一个模型 ID
- regex - oracle中正确的逗号浮动正则表达式是什么
- angular - Firebase 部署的详细日志记录?
- docker - 如何重新运行 continumio/anaconda3 docker 映像?
- jquery - 如何在没有的情况下显示欧芹自定义错误消息
- python-2.7 - Google App engine flex env 中的 time.clock() 和 time.sleep()
- excel - 计算单元格值在行中增加 1 的频率