检查特定属性/参数的所有JSON值

时间:2014-07-29 13:46:38

标签: ajax json

我正在尝试检查“开始”对象的JSON,以及它的值。

例如,如果我的AJAX是

$(document).ready(function () {
    $.ajax({
        url: "Content/events/document.json",
        type: "GET",
        success: function (resp) {
            alert(JSON.stringify(resp)); //Stringify'ed just to see JSON data in alert
        },
        error: function () {
            alert("failed");
        }
    });
});

然后返回

[
 {"title":"Bi-weekly Meeting1","start":"2014-07-09","color":"red"},
 {"title":"Bi-weekly Meeting2","start":"2014-08-06","color":"red"},
 {"title":"Bi-weekly Meeting3","start":"2014-07-23","color":"red"},
 {"title":"Test Event","url":"http://google.com/","start":"2014-07-28"}
]

如何查看每个“开始”值?如果是今天,将该事件存储在不同的数组中?

我只是想跟踪今天的事件,我不知道如何迭代JSON对象。

1 个答案:

答案 0 :(得分:2)

请注意,您应该设置dataType: "json",以便JQuery自动解析作为JSON返回的ajax响应。然后只需遍历您收到的数组,如下所示:

function sameDay( d1, d2 ){
  return d1.getUTCFullYear() == d2.getUTCFullYear() &&
         d1.getUTCMonth() == d2.getUTCMonth() &&
         d1.getUTCDate() == d2.getUTCDate();
}

$(document).ready(function () {
    $.ajax({
        url: "Content/events/document.json",
        type: "GET",
        dataType: "json",
        success: function (resp) {
            resp.forEach(function(item) {
                console.log(item.start);
                if (sameDay( new Date(item.start), new Date)){
                   // This one has today's date!
                }
            });
        },
        error: function () {
            alert("failed");
        }
    });
});