Loading JSON from a local HTML5 web application using JavaScript

I am developing a small HTML5 web application that users can use offline with their cross-platform browsers. They will get the wep application on the CD or USB stick and double-click the HTML file. Then the HTML file loads CSS, JavaScript, etc ... files all locally from the same directory / subdirectories.

So far so good. But I also want to download a file (also local, from the same directory) that contains JSON, and use this data to build the DOM part.

$.getJSON("playlistcontent.json", function (json) { //use the data... }); 

Here I came across the famous

Null origin is not allowed through Access-Control-Allow-Origin

error. There are many resources in this, even fairly similar questions . But since it is intentionally local, the proposed solutions do not work.

However, since AJAX is “asynchronous,” I think there is probably a more “synchronous” or other approach? What about JSONP?

Note. I know that I can launch a browser (especially Chrome) with the security check disabled, but this is not an option for my users.

+4
source share
3 answers

I would use the Felix Kling approach with JSONP. Wrap your data file in a callback function:

 (function(data) { // Do things with your data object here })( // Put your data object here as the argument to the callback ); 

When you include this script file with a tag, the callback function will be executed automatically.

+1
source

I answered a similar question here .

You can use the HTML5 file API , which includes FileReader , and then calls JSON.parse as a result.

+3
source

I like the Felix Kling approach, if you only need JSON data, you can just load your data by setting JS variables and uploading JSON files using script tags. However, if this is not enough for your needs, you can use a solution such as http://www.server2go-web.de/ , which will launch the web server from the CD, therefore bypassing local file restrictions.

+1
source

All Articles