Reputation: 1
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'.
Upvotes: 0
Views: 406
Reputation: 3306
If you're using a compliant HTML5 browser you can use the FileReader API.
See https://stackoverflow.com/a/40946430/2476389
Upvotes: 0
Reputation: 319
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)
Upvotes: 0
Reputation: 21789
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.
Upvotes: 1