0

I am trying to read a local .JSON file and use JSON.parse to put it into a Javascript array. Any other piece of example code would also help. I am unable to do it using the following code, its not able to load a local file.

var xmlhttp = new XMLHttpRequest();
//xmlhttp.overrideMimeType("application/json"); //this line also didnt help
var url = "sample.json";
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function() {

    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        testme(xmlhttp.responseText);
    }
};
xmlhttp.send(); 

function testme(response){

    var record = JSON.parse(response);
    var out = "<table>";

    for(var i = 0; i < record.length; i++) { //prints all the data to html
        out += "<tr><td>" +
        record[i].Name +
        "</td><td>" +
        record[i].City +
        "</td><td>" +
        record[i].Country +
        "</td></tr>";
    }
    out += "</table>";
    document.getElementById("dis").innerHTML = out;
}

the following errors occur

XMLHttpRequest cannot load file:///C:/Practice/CMPE%20273%20refresher/json/Sample.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.transmit1 @ JSON.js:36transmit @ JSON.js:41onclick @ jsonweb.html:11

JSON.js:36 Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///C:/Practice/CMPE%20273%20refresher/json/Sample.json'.

Ankit Rajput
  • 1
  • 1
  • 1
  • 1

3 Answers3

1

You are running the script with the file:// protocol. you won't be able to perform that request with this protocol. you need to install a http server in order to be able to perform the request (even if it's everything in your computer).

there are many lightweight http servers to choose from or you can install nodejs or a xampp/wampp server.

taxicala
  • 21,408
  • 7
  • 37
  • 66
  • 1
    can't it be done without installing server. Can I upload this ".json" file to dropbox and give the url. Would it work then? coz it will be at server then I guess – Ankit Rajput Sep 05 '15 at 03:12
  • I actually do it without installing the server. How can i do it? read a local .json file. Its actually my course assignment. – Ankit Rajput Sep 05 '15 at 03:19
0

Hey your URL is not correct. Please ref this

xmlhttp.open("GET", url,true);

Specifies the type of request, the URL, and if the request should be handled asynchronously or not.

method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)
Community
  • 1
  • 1
Rahul Ahirrao
  • 319
  • 3
  • 10
0

If you're using a compliant HTML5 browser you can use the FileReader API.
See https://stackoverflow.com/a/40946430/2476389

Community
  • 1
  • 1
biomiker
  • 3,108
  • 1
  • 29
  • 26