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>  
 
3
  • Refer stackoverflow.com/questions/7346563/loading-local-json-file.. it may help you Commented Mar 29, 2013 at 12:18
  • I agree with @Amberlamps. Please edit the question and show the error you are getting. Commented Mar 29, 2013 at 12:31
  • Sry i get no error, i get nothing, thats one of the problems Commented Mar 29, 2013 at 12:45

2 Answers 2

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>'));

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the fast reply, where is the }); missing, this is above the </script> tag or not?
@dot I edited. You should try to get used to see symmetry in the code. That's how I spot most obvious errors.
How can i set the correct CORS headers, on this simple server, sry the silly question!
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.