Blake Thiessen
Blake Thiessen

Reputation: 159

How to locally fetch JSON without AJAX

I'm building a game using HTML5 Canvas and Javascript and I'm using JSON formatted tile maps for my levels. The tiles render correctly in FireFox, but when I use Chrome, the JSON fetching fails with a "Origin null is not allowed by Access-Control-Allow-Origin." I was using jQuery's $.ajax command and all my files are in one directory.

I would use this post's solution, but I can't use the web server solution.

Is there any other way to fetch JSON files to be parsed and read from? Something akin to loading an image just by giving the URL? Or is there some way to quickly convert my JSON files into globally available strings so I can parse it with JSON.parse()?

Upvotes: 4

Views: 1592

Answers (2)

cegfault
cegfault

Reputation: 6632

Why is the local web server not an option? Apache is free, can be installed on anything, and easy to use, IMO. Also, for Chrome specifically, look into --allow-file-access-from-files

But if nothing else works, maybe you could just add links to the files in script tags, and then append var SomeGlobalObject = ... to the top of each file. You might even be able to do this dynamically by using JS to append the script tag to head. But in the end, instead of using AJAX, you can just do JSON.parse(SomeGlobalObject)

In other words, load the files into the global namespace by adding script tags. Normally this would be considered bad practice, but used ONLY for testing, in the absence of any other options, it may work.

Upvotes: 1

HBP
HBP

Reputation: 16033

One option which may work for you in Chrome is to invoke the browser with the command line switch --allow-file-access-from-files. This question addresses the issue : Google Chrome --allow-file-access-from-files disabled for Chrome Beta 8

Another possibility is to fetch the JSON data as a script, setting a global variable to the JSON value

Upvotes: 1

Related Questions