2010-08-10 54 views
0

我打电话这个JSON文件:jQuery的JSON AJAX调用检索超过预期

{ 
    "data" : [ 
     { 
      "type" : "file", 
      "target" : "TheGreatest.doc", 
      "workspace" : "Huddle Workspace One", 
      "user" : "Chan Marshall" 
     }, 
     { 
      "type" : "comment", 
      "target" : "martes.mp3", 
      "workspace" : "Huddle Workspace One", 
      "user" : "Fernando Corona" 
     }, 
     { 
      "type" : "file", 
      "target" : "Papalon.pdf", 
      "workspace" : "Huddle Workspace Two", 
      "user" : "Tom Jenkinson" 
     }, 
     { 
      "type" : "whiteboard", 
      "target" : "My Manic & I", 
      "workspace" : "Huddle Workspace One", 
      "user" : "Laura Marling" 
     } 
    ], 
    "error" : false, 
    "code" : 200 
} 

使用jQuery AJAX上的链接的点击:

$('#content > .section > h2 > a').live('click',function() { 

    $('#content > .section > ul').toggle(); 

    /* 
     JSON 
    */ 

    var $jsonURL = 'response.json'; 

    $.ajax({ 
     type: 'GET', 
     url: $jsonURL, 
     dataType: "json", 
     success: function(data){ 

      var $html = ''; 

      $.each(data.data, function(i, data){ 

       if (data.type == 'file') { 
        var $string = 'workspace'; 
       } else if (data.type == 'comment') { 
        var $string = 'file'; 
       } else { 
        var $string = 'workspace'; 
       } 

       $html += '<li class="' + data.type + '">'; 

       $html += '<strong>New ' + data.type + '</strong> was added to the ' + $string + ' '; 

       $html += '<a href="' + data.target + '">' + data.target + '</a> '; 

       $html += '<a href="' + data.workspace + '">' + data.workspace + '</a>'; 

       $html += ' by <a href="#">' + data.user + '</a>'; 

       $html += '</li>'; 

       $('#content > .section > ul').append($html);  

      }); 

     }, 
     error:function (xhr, ajaxOptions, thrownError){ 
      alert(xhr.status); 
      alert(thrownError); 
     }   
    }); 

    return false; 
}); 

而我期待追加4个新名单它带来的元素10.

任何想法,我要去哪里错了?

回答

1

您的$ html变量的范围应该被管理,以便在.each循环中的FIRST操作上设置为“第一项”,并且+而不是+= - 因为您将其附加到循环中,为每个元素“重置”它,您需要将其设置为该循环内第一个元素的起始位置。

我也注意到这个:

 if (data.type == 'file') { 
      var $string = 'workspace'; 
     } else if (data.type == 'comment') { 
      var $string = 'file'; 
     } else { 
      var $string = 'workspace'; 
     } 

可以更简单:

 if (data.type == 'comment') { 
      var $string = 'file'; 
     } else { 
      var $string = 'workspace'; 
     }; 
1

替换此:

$html += '<li class="' + data.type + '">'; 

...这一点:

$html = '<li class="' + data.type + '">'; 
1

是啊,那是因为你定义$html以外的$.each循环,而是继续内追加到它循环。尝试在$.each函数的开头定义$html