如何从json中检索数据

时间:2013-03-20 09:05:31

标签: javascript jquery json

我正在尝试从我从servlet传递的JSON对象中检索数据。但我的钥匙已编号。我需要将这些数字添加到我给键的名称。

我的回答看起来像这样..

{"shareInfo1":[{"uname":"xyz","image":"iVBO..","imname":"ryty","senderPicture":"iVBOR"}],"shareInfo2":[{"uname":"sds","image":"iVBO","imname":"ryty","senderPicture":"iVBOR}],....}

我尝试使用以下代码:

$.ajax({
    type: "GET",
    url: "RetrieveShares",
    data:'action='+encodeURIComponent(action),
    dataType: "json",
    success: function( data, textStatus, jqXHR)
    {
    if(data.success)
    {

for(var z=1;z<=data.loops;z++)
{
len=data["shareInfo"+z].length;
for(var k = len-1;k>=0;k -= 1){
    var newcommhtml = '<div id="S0'+thecid+'" class="snew">';
    newcommhtml = newcommhtml + '<div class="author-image"><img src="data:image/jpeg;base64,'+data["shareInfo"+z][k].senderPicture+'" alt="'+data["shareInfo"+z][k].uname+'" width="100%" height="100%" class="ava"></div><span>'+data["shareInfo"+z][k].uname+' shared the image '+data["shareInfo"+z][k].imname+'</span>';
    newcommhtml = newcommhtml + '<div class="s-content"><div class="s-message"><span>'+nl2br(data["shareInfo"+z][k].message+'</span></div><div class="shpicture">');
    newcommhtml = newcommhtml + '<img src="data:image/jpeg;base64,'+data["shareInfo"+z][k].image+'" alt="'+data["shareInfo"+z][k].imname+'" width="100%" height="100%" class="SharedImage" class="SharedImage" data-id="'+data["shareInfo"+z][k].id+'" data-alid="'+data["shareInfo"+z][k].alid+'" data-shareid="'+data["shareInfo"+z][k].shareId+'">';
    newcommhtml = newcommhtml + '</div></div>';
    var thelm = "#S0"+thecid;
    $('#spscrl').append(newcommhtml);
    $(thelm).hide().fadeIn('slow');
    newcommhtml ='<div class="SPcommentbox">';
    var i=0;
    if(Object.keys(data["shareInfo"+z][k]).length>8)
    {
        var x;
        for(x=data["shareInfo"+z][k].loopreq-1;x>=0;x-=1)
            {
       newcommhtml = newcommhtml + '<div class="comment"><div class="commenter-image"><img src="data:image/jpeg;base64,'+data["shareInfo"+z][k]["commenterPicture"+i]+'" alt="'+data["shareInfo"+z][k]["whocommented"+i]+'" width="100%" height="100%" class="ava"></div><div class="commentername">'+data["shareInfo"+z][k]["whocommented"+i]+'</div><span>'+data["shareInfo"+z][k]["commented"+i]+'</span></div>';
       i+=1;
            }
    }
    newcommhtml = newcommhtml + '<div class="comment"><div class="commenter-image">';
    newcommhtml = newcommhtml +'</div><div class="addcomment"><input type ="text" placeholder="Write a comment..." class="commentbox"></input></div></div>';
    $('#spscrl').append(newcommhtml);
    thecid++;
    }
    $(".primg > img").first().clone().appendTo(".commenter-image");
    }
    }
 },
    error: function(jqXHR, textStatus, errorThrown)
    {
    alert("error"+errorThrown);
    console.log("Something really bad happened " + textStatus);
    },
    });

但它会产生错误TypeError: data[("shareInfo" + z)] is undefined

请有人帮我解决这个问题......谢谢...

3 个答案:

答案 0 :(得分:0)

我知道这并没有直接回答你的问题,但它可能会提供一种解决方法。

如果您能够修改后端,我建议您更改返回数据的格式以使用数组:

{
  "shareInfo":[
     {...},
     {...},
     {...}
  ]
}

然后你可以使用普通的shareInfo [index]和shareInfo.length等。

答案 1 :(得分:-1)

您的Servlet将您的json对象作为String而不是Object发送。所以你首先必须将它转换为JSON对象,如

data = eval( '(' + response + ')' );
data["shareInfo"+z].length;

答案 2 :(得分:-1)

在开始修改DOM元素之前,建立一个更小更简单的结构。

以下是使用jQuerys example函数的$.each();

var data = {
    loops: {
        "shareInfo1": [
            {
                "uname": "xyz",
                "image": "iVBO..",
                "imname": "ryty",
                "senderPicture": "iVBOR"
            },
            {
                "uname": "abc",
                "image": "iVBO..",
                "imname": "smile",
                "senderPicture": "iVBOR"
            }
        ],
        "shareInfo2": [
            {
                "uname": "sds",
                "image": "iVBO",
                "imname": "happy",
                "senderPicture": "iVBOR"
            }
        ]
    }
};

console.log('data', data); // DEBUG

// Iterating the data
$.each(data.loops, function(key, shareInfo) {
    console.log('shareInfo', key, shareInfo); // DEBUG

    $.each(shareInfo, function(key, user) {
        console.log('user', key, user); // DEBUG

        // Username: user.uname
    });

});