Satch3000
Satch3000

Reputation: 49384

JQuery JSON data not displaying

I am having trouble displaying some jason from a page.

The data is there but I think it might have to do with this line:

document.write(fbResults.cats[0].title);

Here is the full html source:

<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script>

    $(document).ready(function() {
        $.getJSON('http://mydomain.com/api/get_cats', function(fbResults) {
            document.write(fbResults.cats[0].title);
        });
    });
</script>

</head>
<body>

</body>
</html>

And here is the data that it's reading:

{"cats":[

{"id":"1","title":"mytitle1","colour":"#EE297C"},
{"id":"2","title":"mytitle2","colour":"#EE412F"},
{"id":"3","title":"mytitle3","colour":"#F5821F"},
{"id":"4","title":"mytitle4","colour":"#00AEEF"},
{"id":"5","title":"mytitle5","colour":"#00B495"},
{"id":"6","title":"mytitle6","colour":"#006476"}

]}

It is not displaying anything on the page.

On firebug console I get this error:

The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must to be declared in the document or in the transfer protocol.

No traces of the json data there

What I'm I doing whong?

Upvotes: 0

Views: 2197

Answers (3)

John Green
John Green

Reputation: 13435

You shouldn't document.write after the page has loaded (which is certainly the case here).

If you want to write it to the page, you'll need to create HTML and append it. Just replace the document.write:

$('body').append('<p>'+fbResults.cats[0].title+'</p>');

Update:

Your example makes a fully qualified URL call. Is that server the exact same one that you're running the page from? If it isn't the XHR will just eat the request (and sometime not tell you). If you need to go cross domain, you'll need to use JSONp. If you're attempting to run this locally while pulling data from the net, it'll break.

Upvotes: 5

Muthukumar M
Muthukumar M

Reputation: 1126

its seems work for me please check this http://jsfiddle.net/TxTCs/1/

Upvotes: 0

Shyju
Shyju

Reputation: 218722

Try this

 $.each(fbResults.cats,function(index,item){
    document.write(item.title);       
  });

Working sample : http://jsfiddle.net/zWhEE/8/

Upvotes: 0

Related Questions