5

I need to read a .json file from my localhost, but it didn't work!

The contents of the file are as follows:

[
 {"source":"tw1", 
  "text":"fubar"}, 

 {"source":"tw2", 
  "text":"foo"}
]

I set up the localhost with the command: python -m http.server 8888 &, which is posted D3.js here.

I wrote the following javascript code:

<script type="text/javascript" src="lib/jquery-1.9.1.js"></script>
   <script>
    $(document).ready(
        $.getJSON("http://localhost/test.json", function(data){
            document.write(data);

    });
    </script>  
 
ggorlen
  • 44,755
  • 7
  • 76
  • 106
dot
  • 486
  • 1
  • 8
  • 17

2 Answers2

4

If you open your server on port 8888, then you must request it on that port :

$.getJSON("http://localhost:8888/test.json", function(data){

But beware that the server must set the correct CORS headers if you want to be able to pass cross domain restrictions.

A third problem is that your code can't compile : you're missing a });. The indentation asymmetry makes it obvious :

$(document).ready(
    $.getJSON("http://localhost:8888/test.json", function(data){
        document.write(data);
    }); // <=== was missing
});

A fourth problem is that you wan't use document.write once the page is loaded. You must write using DOM manipulation methods, like $(document.body).append($('<pre>'+data+'</pre>'));

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Thanks for the fast reply, where is the `});` missing, this is above the `` tag or not? – dot Mar 29 '13 at 12:33
  • @dot I edited. You should try to get used to see symmetry in the code. That's how I spot most obvious errors. – Denys Séguret Mar 29 '13 at 12:37
  • How can i set the correct **CORS headers**, on this simple server, sry the silly question! – dot Mar 29 '13 at 12:58
1

I think the problem is that you're trying to access the json file in your computer, upload your json file to a online server and access that instead of the one that is one your computer.

Erick Mg
  • 41
  • 1
  • 3