JQuery $ajax只获取日期在今天之前的项目
JQuery $ajax only get items with a date before today
我有以下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"处的元素可能会在拼接元素时波动。
相关文章:
- 正在将数据主题添加到所有项目
- 动态地改变“”的URL;添加新项目”;链接使用javascript/jquery
- 如何检查管道中未定义的项目
- 有没有一种方法可以添加相同的项目val=“0”;4〃;到JavaScript中数组的每个对象
- 学生搜索项目jquery/javascript
- 如何获取不属于我项目的上一页的URL
- Dojo:访问dijit.form.Select中单击的项目
- 角度的项目列表 ng 重复,ng 单击显示全宽描述
- 我需要为我的朋友在这个项目上提供帮助
- 如何从 HTML 查询中删除项目
- 在Meteor项目中安装并包含npm模块后出错
- Jquery如何检查今天的时间大于使用给定时间
- 当在Ember中点击一个项目时,我如何将一个活动类添加到项目列表中
- 将单击事件添加到附加的项目中
- 通过另一个php应用程序将我的项目推送到Github存储库中
- 在javascript中搜索项目列表的性能
- 如何将本地依赖项添加到npm项目中
- angularjs移除焦点上的活动类并添加到下一个项目
- JQuery $ajax只获取日期在今天之前的项目
- 项目日期是否在今天的5天内's日期