Ошибка XMLHttpRequest send () из локального файла - PullRequest
0 голосов
/ 01 сентября 2018

Я хочу загрузить файл 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)

}

};

1 Ответ

0 голосов
/ 01 сентября 2018

Вы не можете сделать HttpRequest для локальных ресурсов.

Вам необходимо предоставить этот файл json на вашем локальном сервере.

Например, ваш testjson.json должен быть доступен через http://localhost/testjson.json, а затем сделать HTTP-запрос к этой конечной точке

Этот код работает здесь правильно со мной, console.log(data); в renderHtml () возвращают 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...