【问题标题】:"filter" json through ajax (jquery)通过ajax(jquery)“过滤”json
【发布时间】:2010-02-23 16:45:27
【问题描述】:

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

抱歉所有这些问题,似乎无法找到解决方案.. 任何正确方向的帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: javascript jquery json ajax


    【解决方案1】:

    您很可能需要编写一个过滤器函数:

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

    【讨论】:

    • 您的代码从原始对象中删除了该属性,我认为您希望在该删除循环中使用resultObj,因为将'a' 过滤到'b' 并返回会导致空someDataObject 使用当前代码。
    • 谢谢尼克,修好了。这只是一个疏忽。
    猜你喜欢
    • 2013-01-09
    • 2021-08-06
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多