简体   繁体   中英

Trouble loading data from JSON file into HTML table with js function

The title says it all, I'm struggling to get data from a json file to an HTML table using a js function with jquery, but the data from the json file isn't loading onto the table. I'm also using bootstrap. I got the error Access to XMLHttpRequest at 'file:///C:/Users/Nuno/Desktop/my%20shit/Faculdade/ITW/trabalho%20lab/info.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

JSON:

[
    {"Age": "18", "Email": "qweqwe@ua.pt", "Phone": "123456789", "Adress": "Lisbon", "Languages": "English, Portuguese, (Limited) Spanish"}
]

JS:

    $(document).ready(function(){
  $.getJSON("info.json", function(data){
    var mydata = '';
    $.each(data, function(key,value){
      mydata += '<tr>';
      mydata+= '<td>'+value.age+'</td>';
      mydata+= '<td>'+value.email+'</td>';
      mydata+= '<td>'+value.phone+'</td>';
      mydata+= '<td>'+value.adress+'</td>';
      mydata+= '<td>'+value.languages+'</td>';
      mydata += '</tr>';
    });
    $('#personalInfo').append(mydata);
  });
  });

HTML:

<div class="table-responsive">
          <table class="table table-bordered table-striped" id="personalInfo"> 
              <tr> 
                <th> 
                  Age
                </th> 
                <th> 
                  Email 
                </th> 
                <th> 
                  Phone 
                </th> 
                <th> 
                  Adress
                </th> 
                <th> 
                  Languages
                </th> 
              </tr> 
          </table> 
        </div>

I'm guessing you're using Chrome. There's a restriction in Chrome on accessing any files via xhr requests starting with file: //.

There's more info here http://www.google.com/support/forum/p/Chrome/thread?tid=171316324d16747b&hl=en

Suggestion:

If you are using Google Chrome, it is intentional that AJAX on file:/// paths never works.

crbug/40787

Thanks to all the help, if you ever have this issue check your console. If you get the error "Access to XMLHttpRequest at 'file:///C:/Users/Nuno/Desktop/my%20shit/Faculdade/ITW/trabalho%20lab/info.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https." The problem isn't the code. I managed to get it working using the Live Server extension in VS Code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM