简体   繁体   English

jQuery JSON数据不显示

[英]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: 这是完整的html来源:

<!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. 未声明HTML文档的字符编码。 The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. 如果文档包含来自US-ASCII范围之外的字符,则在某些浏览器配置中,文档将呈现乱码。 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 那里没有json数据的痕迹

What I'm I doing whong? 我在干什么?

You shouldn't document.write after the page has loaded (which is certainly the case here). 页面加载后,您不应该document.write(肯定是这种情况)。

If you want to write it to the page, you'll need to create HTML and append it. 如果要将其写入页面,则需要创建HTML并将其附加。 Just replace the document.write: 只需替换document.write:

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

Update: 更新:

Your example makes a fully qualified URL call. 您的示例进行了完全限定的URL调用。 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). 如果不是,XHR只会处理请求(有时不告诉您)。 If you need to go cross domain, you'll need to use JSONp. 如果您需要跨域访问,则需要使用JSONp。 If you're attempting to run this locally while pulling data from the net, it'll break. 如果您尝试在从网络中提取数据时在本地运行此程序,则它将中断。

Try this 尝试这个

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

Working sample : http://jsfiddle.net/zWhEE/8/ 工作示例: http : //jsfiddle.net/zWhEE/8/

它似乎对我有用,请检查此http://jsfiddle.net/TxTCs/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM