控制进入循环但不在html div中追加和显示数据

时间:2016-05-23 08:52:16

标签: javascript php jquery html json

我有json数据,我希望使用for循环在html div中显示。我在进入循环中的控制但没有在html div中附加和显示数据。

json数据;

[{"id":"15","FirstName":"ranjan","MiddleName":"","LastName":"","Gender":"","Location":"r","Email":"ranjan.gupta.1994@gmail.com","Mobile":""},{"BookTitle":"","BookGenre":"","BookWriter":"","BookDescription":""}]

代码;

$.getJSON(url, function(data) {
            console.log(data);
            if (data) {

                alert("hey got the data" + JSON.stringify(data));
                for (var i = 0; i < data.length; i++) {
                    alert("entered");
                    alert("hey got the data" + JSON.stringify(data[1]));
                    var $appendData =
                        $('<div id="' + data[i].id + '">' + '<p>' 
                        + 'FirstName:' + data[i].data.FirstName + '<br/>' 
                        + 'MiddleName:' + data[i].data.MiddleName + '<br/>' 
                        + 'LastName:' + data[i].data.LastName + '<br/>' 
                        + 'Gender:' + data[i].data.Gender + '<br/>' 
                        + 'Location:' + data[i].data.Location + '<br/>' 
                        + 'Email:' + data[i].data.Email + '<br/>' 
                        + 'Mobile:' + data[i].data.Mobile + '<br/>' 
                        + '</p>' + '</div>').appendTo('#postjson');
                }
            } else {
                return;
            }

//这是我的div

</script>
        <div class="grid" id="postjson"></div> 
        </div>
</div>

1 个答案:

答案 0 :(得分:1)

您的循环错误,只需将所有data[i].data.property替换为data[i].property

<强>的Javascript

    $.getJSON(url,function(data) {

                    console.log(data);
                        if(data){

                            alert("hey got the data"+JSON.stringify(data));
                            for(var i=0; i<data.length; i++) {  
                                    alert("entered");
                                    alert("hey got the data"+JSON.stringify(data[1]));

                                        $('<div id="'+data[i].id+'">'
                                        +'<p>'
                                        +'FirstName:'+data[i].FirstName+'<br/>'
                                        +'MiddleName:'+data[i].MiddleName+'<br/>'
                                        +'LastName:'+data[i].LastName+'<br/>'
                                        +'Gender:'+data[i].Gender+'<br/>'
                                        +'Location:'+data[i].Location+'<br/>'
                                        +'Email:'+data[i].Email+'<br/>'
                                        +'Mobile:'+data[i].Mobile+'<br/>'
                                        +'</p>'
                                        +'</div>').appendTo('#postjson');




                                  }



                               }
                        else {
                            return;             
                        }

JsFiddle