显示json文件时出现问题

时间:2010-10-25 02:55:09

标签: jquery json

我正在尝试使用jquery / json显示这些数组,但我一直未定义。

另外,如何在没有用户点击“A”的情况下显示?

提前致谢

== jSON file ==

// JSON
{
"items": [
{
"title": "welcoem home",
"author": "Charles Dickens"
},
{
"title": "Harry Potter",
"author": "J rowling"
}
]
}

==

<script language="javascript" >
$(document).ready(function() {
  $('#letter-a a').click(function() {
    $.getJSON('q3.json', function(data) {
      $('#dictionary').empty();
      $.each(data, function(entryIndex, entry) {
        var html = '<div class="entry">';
        html += '<h3 class="term">' + entry['title'] + '</h3>';
        html += '<div class="part">' + entry['author'] + '</div>';
        html += '<div class="definition">';
        html += entry['definition'];
        if (entry['items']) {
          html += '<div class="quote">';
          $.each(entry['items'], function(lineIndex, line) {
            html += '<div class="quote-line">' + line + '</div>';
          });
          if (entry['author']) {
            html += '<div class="quote-author">' + entry['author'] + '</div>';
          }
          html += '</div>';
        }
        html += '</div>';
        html += '</div>';
        $('#dictionary').append(html);
      });
    });
    return false;
  });
});


</script>

<link rel="stylesheet" href="json.css" type="text/css" />
</head>

<body>
<div id="container">
        <div id="header">
        <h2>json stuff</h2>
        </div>

        <div class="letters">
                <div class="letter" id="letter-a">
                <h3><a href="#">A</a></h3>
                </div>      

        </div>
        <div id="dictionary">

        </div>
</div>

1 个答案:

答案 0 :(得分:0)

你在这里遇到问题的原因是你在调用$.each(data)时在数组中循环错误的级别。

$.each(data)内部的代码需要循环遍历一个项目数组,但实际上,它是循环遍历data本身的数组键,其中只有一个,即items {1}}。

修复很简单:更改数据in your each()call to be data.items`。

现在代码行如下所示:

$.each(data.items, function(entryIndex, entry) {

希望有所帮助。 (即使有点晚了)

相关问题