只获得带有匹配键的json对象

时间:2016-11-15 14:12:31

标签: jquery json ajax

所以我想做的事情很简单。我有一个显示评论的网站,我有一个管理页面,允许管理员删除评论。但是,我需要在审核之前隐藏评论。

此脚本抓取我的json文件中的每个对象并显示它们:

    $.getJSON("data/comments.json", function(data) {
    var number = [];
    $.each(data, function(index, d) {
        number.push("<div class='comment' id='" + index + "'>" + "<div class='comment-text'>" + d.comment + "</div>" + "<img class='comment-image' src='data/upload/" + d.img + "'>" + "<div class='comment-identifier'><span class='comment-name'>" + "– " + d.name + "</span>" + "<span class='comment-department'>" + ", " + d.department + "</span></div>" + "</div>");
    });
    $("<div/>", {
        "id": "comment-container",
        html: number.join("")
    }).appendTo("#comment-layout");
});

每个json对象在创建时都会应用“approved:false”键。我怎样才能让上面的脚本只拉出对象上带有“approved:true”的对象?

2 个答案:

答案 0 :(得分:0)

您可以在将其推送到阵列之前检查它是否已获批准。但它不会阻止数据在客户端接收。

$.getJSON("data/comments.json", function(data) {
    var number = [];
    $.each(data, function(index, d) {

        if (d.approved == false)
           continue;

        number.push("<div class='comment' id='" + index + "'>" + "<div class='comment-text'>" + d.comment + "</div>" + "<img class='comment-image' src='data/upload/" + d.img + "'>" + "<div class='comment-identifier'><span class='comment-name'>" + "– " + d.name + "</span>" + "<span class='comment-department'>" + ", " + d.department + "</span></div>" + "</div>");
    });
    $("<div/>", {
        "id": "comment-container",
        html: number.join("")
    }).appendTo("#comment-layout");
});

如果您不希望数据到达客户端,则应过滤数据服务器端,并使用$ .ajax而不是$ .getJSON:

$.ajax({
   url: 'routeToYourFilterFunction',
   success: function(data){
      number.push();
   }
});

答案 1 :(得分:-1)

您可以在$.each功能中检查评论是否获得批准。

$.each(data, function(index, d) {
   if(d.approved){
        number.push("<div class='comment' id='" + index + "'>" + "<div class='comment-text'>" + d.comment + "</div>" + "<img class='comment-image' src='data/upload/" + d.img + "'>" + "<div class='comment-identifier'><span class='comment-name'>" + "– " + d.name + "</span>" + "<span class='comment-department'>" + ", " + d.department + "</span></div>" + "</div>");
   }
});