Reputation: 1564
I have a JSON file stored in the same folder as an HTML file for a webpage I'm working on. This HTML file has a script with a function that takes data in a variable in JSON form. I'm having trouble getting the contents of the JSON file into a variable in my HTML file to be used by the function. I am running the HTML file locally.
I've tried the following:
$(function(){
$.getJSON("./data.json", function(jsdata) {
json = jsdata;
console.log(json);
});
});
However, it only results in: XMLHttpRequest cannot load file
. Is there any way to parse a local JSON file in Javascript?
The JSON was validated using http://jsonlint.com/
Using "data.json" gives the same error as before.
Upvotes: 1
Views: 894
Reputation: 1593
You cannot load a local file using $.getJSON
in jquery.
You have to set a valid url
of your file inside of your project, not a local file path because browser prevents it from loading for some security reason.
Upvotes: 2
Reputation: 87203
The URL provided is wrong.
Use following:
$(function () {
var baseUrl = 'http://....'; // Your base url of app
// Use the absolute URL in here
$.getJSON( baseUrl + "/data.json", function (jsdata) {
json = jsdata;
console.log(json);
});
});
Upvotes: 1
Reputation: 3330
try this code
$.ajax({
url: "./data.json", // or "/data.json",
type: "GET",
dataType: "json"
})
Upvotes: 0
Reputation: 32713
Do not use a .
. If the json file is in the same folder as the location your js is running (i.e. your html file), it should be this:
$(function(){
$.getJSON("data.json", function(jsdata) {
json = jsdata;
console.log(json);
});
});
Upvotes: 3
Reputation: 4224
Dot in the url is causing the problem
Use this:
$.getJSON("/data.json", function(jsdata) {
json = jsdata;
console.log(json);
});
Upvotes: 1