javascript - Ajax 请求包含 JSON - 就绪状态 4,状态 0

标签 javascript html ajax

我正在对我网站中包含的 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"}
]
}

最佳答案

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

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

  3. 打开浏览器类型如下: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/

相关文章:

html - 如何删除底部伪元素之后和之前的空格?

javascript - 根据 slider 的值将不同的数据推送到数组

javascript - HTML 标签 <a> href 和 onclick

javascript - Yii2 - 将 ID 传递给 GridView 中的另一个属性

javascript - 是否可以在溢出的情况下缩小字体大小?

javascript - setTimeout方法执行一次

javascript - 在 Grunt 插件配置中动态生成映射键

javascript - 防止点击暂停视频

php - 没有使用 application/json 获取 POST 数据

javascript - Easy JS 变量传递问题