Trying to load local JSON file to show data in a html page using JQuery
As the jQuery API says: "Load JSON-encoded data from the server using a GET HTTP request."
http://api.jquery.com/jQuery.getJSON/
So you cannot load a local file with that function. But as you browse the web then you will see that loading a file from filesystem is really difficult in javascript as the following thread says:
Local file access with javascript
Load a JSON file in local system using jQuery/Javascript
As you've seen - you can't make AJAX requests to the local filesystem as it's a huge security issue. The only workaround for this is for the user to manually enable settings in their browser (which is not a great idea anyway). If you do not want this then you will have to use a central server for all requests.
The alternative is to avoid using AJAX by including the new.json
file in the page using an extra <script />
tag. You will also need to assign the object to a variable in the file, something like this:
// new.json
var newJson = {"a": [{"name":"avc"}, {"name":"Anna"}, {"name":"Peter"}]}
Then in gary.html
:
<head>
<script src="jquery.js"></script>
<script src="new.json"></script>
<script>
$(function() {
newJson.a.forEach(function(item) {
console.log(item.name);
});
})
</script>
</head>
Unable to load data from local json file using jQuery
change data.person
to data.employees
, wrap the code in a document ready statement
https://plnkr.co/edit/PemDjZFAsFCcH16NfdQu?p=preview
Loading local JSON file
$.getJSON
is asynchronous so you should do:
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
Related Topics
How to Open New Tab in JavaScript Without Switching to the New Tab
Check If HTML Snippet Is Valid with JavaScript
Clearing My Form Inputs After Submission
Saving and Loading an Image from Localstorage
Possible to Associate Label with Checkbox Without Using "For=Id"
Img-Src' Was Not Explicitly Set, So 'Default-Src' Is Used as a Fallback
Multiple Select Limit Number of Selection
How to Show and Hide Input Fields Based on Radio Button Selection
Load JSON from Local File with Http.Get() in Angular 2
Html5 <Audio> Playback with Fade in and Fade Out
JavaScript on the Bottom of the Page
Increment a Number in a String in with Regex
Addeventlistener for Keydown on Canvas
Replace Multiple Whitespaces with Single Whitespace in JavaScript String