需要一些json和jQuery的帮助

时间:2011-05-14 04:42:57

标签: php jquery json each

无论出于什么原因,我无法弄清楚json,我不明白为什么我不能让它工作。

我的json回来了:

{"lists":[{"item":"1","count":"5"}]}
{"lists":[{"item":"1","count":"5"}]}
{"lists":[{"item":"1","count":"5"}]}
{"lists":[{"item":"1","count":"5"}]}
{"lists":[{"item":"1","count":"5"}]}
等等等等

现在我试图通过使用:

来检索它
$.getJSON("lists.php",
  {id: aid},function(data){
  $.each(data.lists, function(i, info) {
      $('.container').append(info.item+info.count);
  });
});

但我在这里没有得到任何数据。谁能指出我正确的方向?

});

3 个答案:

答案 0 :(得分:4)

您需要返回如下数据:

{
  "lists":[
    {"item":"1","count":"5"},
    {"item":"1","count":"5"},
    {"item":"1","count":"5"},
    {"item":"1","count":"5"},
    {"item":"1","count":"5"}
  ]
}

在你的php中,执行以下操作:

echo "{\"lists\":[";
foreach ($lists as $obj) {
  echo "{\"item\": \"" . $obj->item . "\", ";
  echo "\"count\": \"" . $obj->count . "\"},";
}
echo "]}\n";

希望有所帮助!

答案 1 :(得分:3)

看起来你习惯了URL参数的编码方式。 JSON的工作方式不同。

如果您希望对象包含包含数组的键lists,则应该返回JSON,如下所示:

{
  "lists": [
    {"item":"1","count":"5"},
    {"item":"1","count":"5"},
    {"item":"1","count":"5"},
    {"item":"1","count":"5"},
    {"item":"1","count":"5"}
  ]
}

答案 2 :(得分:1)

以上是无效的JSON。我相信这是您正在寻找的语法,它将被描述为“包含列表属性的对象”:

{"lists":[{"item":"1","count":"5"},{"item":"1","count":"5"},{"item":"1","count":"5",{"item":"1","count":"5"},{"lists":[{"item":"1","count":"5"}]}

您可能需要调整后端代码,以便每次向“lists”数组添加新成员而不是全新的“列表”。