如何使用jquery使用ajax调用中的数组生成每个元素的元素?

时间:2014-08-28 09:05:23

标签: php jquery ajax each

我想使用jquery创建注释,这是ajax调用的php文件:

require_once '../Classes/MainController.php';
$mc = MainController::getInstance();
foreach ($mc->getThreadComments($_POST['thread_id']) as $comments)
print json_encode($comments);

这是ajax调用的输出(2条评论):

{
    "0": "6",
    "id": "6",
    "1": "10",
    "user_id": "10",
    "2": "3",
    "thread_id": "3",
    "3": "ba nu fii    nebuuun cum e piesa asta !",
    "comment": "Damn son, this is the shit!"
} {
    "0": "7",
    "id": "7",
    "1": "10",
    "user_id": "10",
    "2": "3",
    "thread_id": "3",
    "3": "Omg this hits so  fucking hard , bass too stronk !",
    "comment": "Omg this hits so fucking hard , bass too stronk !"
}

我想将其转换为html,类似于:

 <div class="large-2 columns small-3"><p> User id </p></div>
 <div class="large-10 columns"><p > Comment </p></div>

如果我希望在页面加载后自动响亮,脚本会是什么样子?我知道它与each()有关,但我真的不知道如何使用它。

1 个答案:

答案 0 :(得分:1)

            $.post("<?php echo site_url("assignment/getcomments"); ?>" 
                    ,{ "csrf_aimsis":csrf_key, 
                       "assignment_id":assignment_id,
                       "start": start
                     },
                function(data)
                {
                    if(data != null)
                    {
                        if(data.error == undefined)
                        {
                            for(var i = 0; i < data.length; i++)
                            {
                                var wrapper = $("<div></div>");

                                var div_1 = $("<div></div>");
                                div_1.attr("class", "large-2 columns small-3");
                                div_1.append(data[i].user_id);

                                var div_2 = $("<div></div>");
                                div_2.attr("class", "large-10 columns");
                                div_2.append(data[i].comment);

                                wrapper.append(div_1);
                                wrapper.append(div_2);

                                $(document).append(wrapper);


                            }
                        }
                        else
                          alert(data.error);
                    }

                  $(".loading").hide();
                },"json").error(errorAjax); 

首先进行ajax调用,然后遍历其数据并附加到包装器div,最后追加到文档本身,或者你可以将它附加到某个元素。