javascript - "filter"json 通过 ajax (jquery)

标签 javascript jquery json ajax

我正在尝试通过 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/

相关文章:

javascript - ReactJS 中的 Bootstrap 行

javascript - 如何使用 Google Apps 脚本自动下载 Google 电子表格数据

javascript - 在散点上添加工具提示,为 D3.js 版本 4 生成错误

jquery - 如何将 CSS 事件与 jQuery 样式结合使用?

javascript - 文本框和选择框将值组合在单个文本中(第一个 tb 值,然后是 sb 值)

javascript - 如何在javascript函数外传递值?

Javascript 代码块在返回被调用函数的结果之前完成?我缺少什么?

javascript - 如何用json数据和ajax创建一个动态的jquery数据表?

java - 无法遍历 JSON 数组

c# - 使用 JSON.net 序列化 Dictionary<int,object>?