我正在尝试通过 ajax 过滤 json 数组,但不确定如何操作。
{
posts: [{
"image": "images/bbtv.jpg",
"group": "a"
}, {
"image": "images/grow.jpg",
"group": "b"
}, {
"image": "images/tabs.jpg",
"group": "a"
}, {
"image": "images/bia.jpg",
"group": "b"
}]
}
我想要它,以便我只能显示 A 组或 B 组中的项目。
我必须如何更改我的 ajax 才能过滤内容?
$.ajax({
type: "GET",
url: "category/all.js",
dataType: "json",
cache: false,
contentType: "application/json",
success: function(data) {
$('#folio').html("<ul/>");
$.each(data.posts, function(i,post){
$('#folio ul').append('<li><div class="boxgrid captionfull"><img src="' + post.image + '" /></div></li>');
});
initBinding();
},
error: function(xhr, status, error) {
alert(xhr.status);
}
});
另外,我怎样才能让每个链接都处理过滤器?
<a href="category/all.js">Group A</a> <a href="category/all.js">Group B</a>
抱歉所有这些问题,似乎无法找到解决方案.. 任何在正确方向上的帮助将不胜感激。
谢谢!
最佳答案
您很可能需要编写一个过滤器函数:
function filterGroup(obj, filteredGroup) {
var resultObj = $.extend({},obj);
for (var i in obj) {
if ( obj.hasOwnProperty(i) ) {
if ( obj[i].group && obj[i].group !== filteredGroup ) {
delete resultObj[i];
}
}
}
return resultObj;
}
然后您只需通过该过滤器运行您的数据。您可能还想切换到带有一堆像这样的 JSON 的 POST。
$.ajax({
type: "POST",
url: "category/all.js",
dataType: "json",
cache: false,
data: {"posts": filterGroup(posts, 'a')},
contentType: "application/json",
success: function(data) {
$('#folio').html("<ul/>");
$.each(data.posts, function(i,post){
$('#folio ul').append('<li><div class="boxgrid captionfull"><img src="' +
post.image + '" /></div></li>');
});
}
});
大部分代码都是假设的,因为我不知道你在做什么,但它应该让你接近。只是不要指望能够复制/粘贴它。例如,假设您实际上将数据变量命名为 posts
。
要制作链接运行代码,您需要附加点击处理程序并识别每个链接。我假设您为每个(filterA 和 filterB)添加了一个类名:
$('.filterA').click(function(){
filterGroup(someDataObject, 'a');
return false;
});
$('.filterB').click(function(){
filterGroup(someDataObject, 'b');
return false;
});
关于javascript - "filter"json 通过 ajax (jquery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2319972/