【问题标题】:XMLHttpRequest send() from local file failed来自本地文件的 XMLHttpRequest send() 失败
【发布时间】:2018-09-01 23:27:52
【问题描述】:

我想从计算机中的本地文件加载 JSON 文件,并且我已经下载了 Node.js 并启动了它。但它一直显示此消息“加载失败...仅支持跨源请求...”

F12 还向我展示了 ourRequest.send(); 行中的文件

这是我的代码...

var btn=document.getElementById("btn");
var tajweedContainer=document.getElementById("rule_info");
btn.addEventListener("click",function(){

var ourRequest= new XMLHttpRequest();
ourRequest.open('GET','testjson.json');
ourRequest.onload=function(){
var ourData=JSON.parse(ourRequest.responseText);
    renderHtml(ourData);
}
ourRequest.send();

});
function renderHtml(data){
    var htmlString="";
    for(var i=0;i<data.length;i++){
        htmlString="<p>"+data[i].surah+data[i].ayah+"the grammar ";
       for(var ii=0;ii<data[i].annotations;ii++){
           htmlString+=data[i].annotations.end[ii]+data[i].annotations.rule[ii]+data[i].annotations.start[ii]

    }
htmlString+=".</p>";
tajweedContainer.insertAdjacentHTML('beforeend',htmlString)

}

};

【问题讨论】:

  • 从节点本地服务器打开页面并从同一服务器实例提供 json 文件
  • 你的意思是我打开节点并写http-server“文件位置”

标签: javascript html json ajax


【解决方案1】:

您不能向本地资源发出 HttpRequest。

您需要在 localhost 服务器中提供此 json 文件。

例如,您的 testjson.json 应该可以通过 http://localhost/testjson.json 访问,然后向此端点发出 HTTP 请求

这段代码在我这里可以正常工作,renderHtml() 中的console.log(data); 正在返回testjson.json

<button id="btn">Render</button>
<div id="rule_info"></div>

<script>
var btn = document.getElementById("btn");
var tajweedContainer=document.getElementById("rule_info");

btn.addEventListener("click",function(){
var ourRequest= new XMLHttpRequest();
ourRequest.open('GET','http://localhost/testjson.json');
ourRequest.onload=function(){
var ourData=JSON.parse(ourRequest.responseText);
    renderHtml(ourData);
}
ourRequest.send();

});
function renderHtml(data){
    console.log(data);

    var htmlString="";
    for(var i=0;i<data.length;i++){
        htmlString="<p>"+data[i].surah+data[i].ayah+"the grammar ";
       for(var ii=0;ii<data[i].annotations;ii++){
           htmlString+=data[i].annotations.end[ii]+data[i].annotations.rule[ii]+data[i].annotations.start[ii]

    }
htmlString+=".</p>";
tajweedContainer.insertAdjacentHTML('beforeend',htmlString)

}

};
</script>

【讨论】:

  • 我按照你说的做了,但它向我显示了这个错误“GET localhost/testjson.json0 () (anonymous) @ jsTajweed.js:11”,该行包含ourRequest.send();
  • 如果您在浏览器中输入localhost/testjson.json,您可以访问它吗?
  • 127.0.0.1:8080/testjson.json>>>>> 我可以通过这个链接访问,但是当我粘贴到我的代码中时,它给出了这个错误“无法加载127.0.0.1:8080/testjson.json:没有'Access-Control-Allow-Origin ' 请求的资源上存在标头。因此不允许访问源 'null'。"
  • Origin 'null' is therefore not allowed access. 通常是本地文件系统file:///,确保你通过http://访问你的HTML页面
猜你喜欢
  • 2011-12-02
  • 2019-06-27
  • 2011-11-15
  • 1970-01-01
  • 2011-10-31
  • 2019-12-07
  • 2013-04-06
  • 2011-01-15
  • 1970-01-01
相关资源
最近更新 更多