KrankyCode
KrankyCode

Reputation: 451

Do we need a web server (like Apache) to access a .json file?

I was trying to read an info.json file, using the jQuery API. Please find the code below, which is part of test.html.

$.getJSON('info.json', function(data) {
  var items = [];
  $.each(data, function(key, val) {
    items.push('<li id="' + key + '">' + val + '</li>');
  });

The test.html file resides on my local machine and when I try to open it in the browser, the Ajax call is not getting triggered and the info.json file is not read.

Is it not working because I don't have a web server? Or am I doing anything wrong in the code? (I don't see any errors in the Firebug console though).

Thanks in advance.

Upvotes: 3

Views: 3423

Answers (4)

Patrick Trester
Patrick Trester

Reputation: 1

By putting your JSON string into a text file and loading it in a iframe, you can extrapolate the data. (Most browsers can load .txt files in iframes.)

var frame = document.createElement("IFRAME"); //Create new iframe
var body = document.body;
frame.onload = function() { //Extrapolate JSON once loaded
  data = JSON.parse(frame.contentDocument.documentElement.innerText); //Loads as a global.
  body.removeChild(frame); //Removes the frame once no longer necessary.
}
frame.style.display = "none"; //Because the frame will have to be appended to the body.
body.appendChild(frame);
frame.src = "your JSON.txt"; //Select source after the onload function is set.

Upvotes: 0

hamilton.lima
hamilton.lima

Reputation: 1918

Install a small webserver like http://jetty.codehaus.org/jetty/ easy to install, and small download ;)

Upvotes: 0

Sachin Jain
Sachin Jain

Reputation: 21842

You will always have to host your site from where you are making AJAX call. Otherwise it will throw this exception.

origin null is not allowed by access-control-allow-origin

Host your page on localhost server and I guess everything will work nicely.

Upvotes: 2

Thilo
Thilo

Reputation: 262774

While technically you don't need a web server for this, some of the libraries you use to abstract network access may not work with local files and some browsers don't let local files do a lot, so something like a little test web server for static files would be very useful for your development and testing.

Upvotes: 1

Related Questions