Trying to Load Local JSON File to Show Data in a HTML Page Using Jquery

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



Leave a reply



Submit