开发者

"filter" json through ajax (jquery)

I'm trying to filter the json array through ajax and not sure how to do so.

{
  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"
  }]
}

i want it so that i can only show items in group A or group B.

how would i have to change my ajax to filter through the content?

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

});

Also, how can I can I make each link process the filter?

<a href="category/all.js"&g开发者_JAVA百科t;Group A</a> <a href="category/all.js">Group B</a>

Sorry for all these questions, can't seem to find a solution.. Any help in the right direction would be appreciated.

Thanks!


You'll need to write a filter function, more than likely:

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

Then you'd just run your data through that filter. You'll also probably want to switch to a POST with a bunch of JSON like this.

$.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>');
    });
  }
});

Most of this code is hypothetical since I don't know exactly what you're doing, but it should get you close. Just don't expect to be able to copy/paste it. This assumes you actually named your data variable as posts for instance.

To make a link run code, you'll need to attach a click handler and identify each link. I'll assume you added a classname to each (filterA and filterB):

$('.filterA').click(function(){
  filterGroup(someDataObject, 'a');
  return false;
});
$('.filterB').click(function(){
  filterGroup(someDataObject, 'b');
  return false;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜