jQuery JSON AJAX调用检索超过预期

时间:2010-08-10 11:48:28

标签: jquery ajax json

我正在调用此JSON文件:

{
    "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个。

关于我哪里出错的任何想法?

3 个答案:

答案 0 :(得分:1)

替换它:

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

......用这个:

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

答案 1 :(得分:1)

是的,这是因为您在$html循环之外定义$.each,但继续在循环内追加它。尝试在$html函数的开头定义$.each

答案 2 :(得分:1)

应管理$ html变量的范围,以便在.each循环中的FIRST操作中将其设置为“{1}}而不是+的”设置为第一项“ - 就像您一样将它附加到循环中然后为每个元素“重置”它,你需要在该循环中首先将它设置为元素的开始。

我也注意到了这一点:

+=

可能更简单:

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