JQuery $ajax只获取日期在今天之前的项目

JQuery $ajax only get items with a date before today

本文关键字:今天 项目 取日期 ajax 获取 JQuery      更新时间:2023-09-26

我有以下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 仅包含"日期"早于或等于 2016-01-27 15:26:17(示例时间点)的项目。 $.ajax 是否有允许我执行过滤的功能?

如果是这样,我将如何去做?

您的示例数据缺少引号,但请修复此问题,您只需将 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/

如果不知道您正在使用的服务,就不可能说出如何获得您想要的结果。但是,如果您的唯一目标是获取该数组的子集,则只需在结果数组中执行如下所示的循环。

// 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);
    }
}

请注意,向后循环遍历数组很重要,因为索引"i"处的元素可能会在拼接元素时波动。