简体   繁体   English

我无法从JSON文件检索数据

[英]I can't retrieve data from a JSON file

I've created a website in wordpress and I'm using wordpress json API to retrieve data for a web-app I'm developing. 我已经在wordpress中创建了一个网站,并且正在使用wordpress json API来检索正在开发的网络应用程序的数据。 The json API is working fine: http://danielvivancos.com/edu/wordpress/?json=1 I get my Json file. json API工作正常: http ://danielvivancos.com/edu/wordpress/?json=1我得到了我的Json文件。 But now I'm trying to print it in my html page with getjson jquery method. 但是现在我正在尝试使用getjson jquery方法将其打印在我的html页面中。 First I'm just just trying to display in a div some information from the json file to check that it is working but i don't know why it's not. 首先,我只是想在div中显示json文件中的一些信息,以检查它是否正常工作,但我不知道为什么不行。 Here you can check my script: 在这里您可以检查我的脚本:

$(document).ready(function (){
$("#btn382").click(function(){       

    $.ajaxSetup({ cache: false });

    $.getJSON("http://danielvivancos.com/edu/wordpress/?json=1&count=1", function(data){
        var html = [];


        $.each(data.posts.author, function(index, author){           
            html.push("id : ", author.id, ", ",
                      "slug : ", author.slug, ", ",
                      "name : ", author.name, "<br>");
        });


        $("#div381").html(html.join('')).css("background-color", "orange");
    }).error(function(jqXHR, textStatus, errorThrown){ /* assign handler */
        /* alert(jqXHR.responseText) */
        alert("error occurred!");
    });
});
});

And of course I have the #div381 created. 当然,我创建了#div381。 I don't know what I'm doing wrong but I'm really stuck. 我不知道自己在做什么错,但是我真的很困。 Any help would be appreciated!! 任何帮助,将不胜感激!!

EDIT : The console error is: Cannot read property 'length' of undefined. 编辑 :控制台错误是:无法读取未定义的属性“长度”。

SOLVED : I've changed the coma for a plus sign and changed the way of iterating through the file just as is explained below in one of the the answers. 解决 :我已将加号的逗号更改为逗号,并更改了遍历文件的方式,如下面的答案之一中所述。

It seems the type of the posts is an array and the first element is a hash which contains author . posts的类型似乎是数组,而第一个元素是包含author的哈希。

Try to rewrite 尝试重写

$.each(data.posts[0].author, ...

UPDATE UPDATE

html.push("status : ", data.status, ", ",
   "count : ", data.count, ", ",
   "pages : ", data.pages, "<br>"); 
$.each(data.posts, function(index, post){
   html.push("id : ", post.author.id, ", ",
     "slug : ", post.author.slug, ", ",
     "name : ", post.author.name, "<br>");
});

The posts property in your JSON File is an array . JSON文件中的posts属性是一个array

So you need to loop through that array first, to access the author property! 因此,您需要首先遍历该数组,以访问author属性!

$.each(data.posts, function(i, post) {
    var author = post.author;
});

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

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