dongsuiying7773 2017-03-17 06:44
浏览 94
已采纳

使用jQuery和PHP在div中显示循环中的JSON数据

I am using jQuery and JSON to get data from database

$("#openNotification").on('click', function(e)
{
    ID = "a";
    $.ajax(
    {
        url: "notificationDetail",
        type: "POST",
        data:
        {
            designationID: ID
        },
        dataType: "JSON",
        success: function (jsonStr)
        {
            $(".processingNotification").hide();

            var jSonLength = jsonStr.length;

            for (var i=0; i<jSonLength; i++)
            {
                var userAvatar = jsonStr[0].userAvatar;

                var newrow = "<div class='subNotification'><img src='assets/img/avatar/"+userAvatar+"'/></div>";


            }


            $(".opened_page").html(newrow);
        }
    });
});

HTML

<div class="opened_page"></div>

When I click #openNotification I can see the jSon data from PHP

enter image description here

But when I want to display the data to .opened_page it only show 1 data.

  • 写回答

2条回答 默认 最新

  • dongzuo4666 2017-03-17 06:47
    关注

    you are replacing with new value, code should be

    var newrow = '';
    for (var i=0; i<jSonLength; i++)
    {
         var userAvatar = jsonStr[0].userAvatar;
         newrow += "<div class='subNotification'><img src='assets/img/avatar/"+userAvatar+"'/></div>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • douyan1453 2017-03-17 07:04
    关注

    You can also use jQuery append() function here.

    For eg.

    for(var i = 0; i < jSonLength; i++){
       var userAvatar = jsonStr[i].userAvatar;
       $(".opened_page").append("<div class='subNotification'><img src='assets/img/avatar/"+userAvatar+"'/></div>");
    }
    

    So your final code would be like,

    $("#openNotification").on('click', function(e){
        ID = "a";
        $.ajax({
            url: "notificationDetail",
            type: "POST",
            data: {
                designationID: ID
            },
            dataType: "JSON",
            success: function (jsonStr){
                $(".processingNotification").hide();
                var jSonLength = jsonStr.length;
    
                for(var i = 0; i < jSonLength; i++){
                    var userAvatar = jsonStr[i].userAvatar;
                    $(".opened_page").append("<div class='subNotification'><img src='assets/img/avatar/"+userAvatar+"'/></div>");
                }
            }
        });
    });
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 我需要在PC端 开两个抖店工作台客户端.(语言-java)
  • ¥15 有没有哪位厉害的人可以用C#可视化呀
  • ¥15 可以帮我看看代码哪里错了吗
  • ¥15 设计一个成绩管理系统
  • ¥15 PCL注册的选点等函数如何取消注册
  • ¥15 问一下各位,为什么我用蓝牙直接发送模拟输入的数据,接收端显示乱码呢,米思齐软件上usb串口显示正常的字符串呢?
  • ¥15 Python爬虫程序
  • ¥15 crypto 这种的应该怎么找flag?
  • ¥15 代码已写好,求帮我指出错误,有偿!
  • ¥15 matlab+波形匹配算法