如何使用Jquery显示JSONArray项目

时间:2013-02-21 17:22:39

标签: javascript jquery

我正在尝试使用Jquery显示从网页中的数据库中检索的项目。但是我的代码没能做到这一点。任何人都告诉我如何显示数组中的项目。

我的代码是:

  success: function( data, textStatus, jqXHR) 
        {
            if(data.success)
            {
                for(var i = 0,len=data.length;i<len;i += 1){
                    if(data.commentInfo[i].success)
                    {
                        var newcommhtml = '<div id="c0'+thecid+'" class="cnew clearfix"> <section class="c-author">';
                        newcommhtml = newcommhtml + '<h3>Anonymous</h3>';
                        newcommhtml = newcommhtml + '<span class="pubdate">'+month+' '+day+', '+year+'</span> </section>';
                        newcommhtml = newcommhtml + '<section class="c-content">';
                        newcommhtml = newcommhtml + '<img src="images/green-avatar.png" alt="avatar" width="80" height="80" class="ava">';
                        newcommhtml = newcommhtml + '<p>'+nl2br(data.commentInfo[i].comment)+'</p> </section></div>';

                        var thelm = "#c0"+thecid;
                        commwrap.append(newcommhtml);
                        $(thelm).hide().fadeIn('slow');

                        setTimeout(function() { $(thelm).addClass('green'); }, 800);

                        $("#comm").val("");
                        thecid++;

                    }
                    else
                        {
                        alert("dsdsds");
                        }
                }
                    if(errorspan.html() != null) {
                        errorspan.remove();
                    }
            }

          },
     error: function(jqXHR, textStatus, errorThrown)
      {
         alert("error"+errorThrown);
         console.log("Something really bad happened " + textStatus);
      },

从服务器收到的回复是:

 {"success":true,"commentInfo":[{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"},{"uname":"shyam","comment":"ghg"}]} 

请有人帮助我......谢谢....

1 个答案:

答案 0 :(得分:3)

data是一个不是数组的对象。

如果您希望在数据中定位commentInfo,您可以这样做:

for (var i = 0; i < data.commentInfo.length; i++) {
   var item = data.commentInfo[i];
}