JQuery $ ajax只能在今天之前获得具有日期的项目

时间:2016-01-27 18:55:29

标签: javascript jquery json ajax

我有以下jQuery代码:

var fetchResults = function () {
    return JSON.parse($.ajax({
        type: 'GET',
        url: '/Search/GetResults',
        async: false,
        dataType: 'json'
        }).responseText);
    };

/ Search / GetResults返回JSON格式的数据字符串。 / Search / GetResults不接受任何条件。

返回的数据看起来有点像这样:

[{"title":"Sample 1 Title","Sample 1 Description":"","headline":"Sample 1 Headline","body":"","date":"2016-01-17 5:30:00"},{"title":"Sample 2 Title","Sample 2 Description":"","headline":"Sample 2 Headline","body":"","date":"2016-01-22 7:45:17},{"title":"Sample 3 Title","Sample 3 Description":"","headline":"Sample 3 Headline","body":"","date":"2016-01-27 15:26:17"},{"title":"Sample 3 Title","Sample 3 Description":"","headline":"Sample 4 Headline","body":"","date":"2016-01-29 18:00:00"}]

使用上面显示的示例数据,我希望fetchResults只包含" date"是等于或等于2016-01-27 15:26:17(一个示例时间点)。是否有$ .ajax函数可以让我执行过滤?

如果是这样,我该怎么做呢?

2 个答案:

答案 0 :(得分:1)

如果不了解您所服务的服务,就无法说出如何获得您所寻求的结果。 然而,如果您的唯一目标是获取该数组的子集,您可以通过结果数组执行如下循环。

// I'm using the name "results" for the variable where you store
//  the results of your Ajax call

// Loop through every element of results
for(var i = results.length; i--;) {
    // Determine if the date is in the past
    if(Date.parse(results[i].date) < new Date()) {
        // Remove the result
        results.splice(i, 1);
    }
}

请注意,将数组向后循环非常重要,因为索引&#34; i&#34;否则会在你拼接元素时波动。

答案 1 :(得分:1)

您的示例数据缺少引号但修复了该问题,您只需将dataFilter添加到ajax:

var fetchResults = function() {
  return JSON.parse($.ajax({
    type: 'GET',
    url: '/Search/GetResults',
    async: false,
    dataType: 'json',
    dataFilter: function(mydata) {
      var pdata = JSON.parse(mydata);
      var startDate = new Date("2016-01-27 15:26:17");// hard coded :)
      var dateLess = pdata.filter(function(r) {
        //console.log("r",r.date);// each date
        var d = new Date(r.date);
        return d <= startDate
      });
      return dateLess;//filtered data
    }
  }).responseText);
};

返回:

[{
  "title": "Sample 1 Title",
  "Sample 1 Description": "",
  "headline": "Sample 1 Headline",
  "body": "",
  "date": "2016-01-17 5:30:00"
}, {
  "title": "Sample 2 Title",
  "Sample 2 Description": "",
  "headline": "Sample 2 Headline",
  "body": "",
  "date": "2016-01-22 7:45:17"
}, {
  "title": "Sample 3 Title",
  "Sample 3 Description": "",
  "headline": "Sample 3 Headline",
  "body": "",
  "date": "2016-01-27 15:26:17"
}]

以下是在ajax之外工作的示例过滤器:https://jsfiddle.net/2wbdpfos/