在jQuery AJAX中排除foreach循环中的某些对象属性

时间:2014-09-01 13:46:47

标签: javascript jquery ajax

Fiddle Example

我有一个php文件,用于返回主要内容数据的json数据以及用于交易数据的附加属性。我想知道在重复foreach循环中的数据时是否可以排除分页数据的属性以避免未定义的警告。

var data = [{"larger_than_1":true,"current_page_no":110,"otherpageno":"100,101,102,103,104,105,106,107,108,109,111,112,113,114,115,116,117,118","current_not_equal_total":"true","nextpage":111,"website":"www.google.com"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"}]; 

分页数据始终是第一个属性,我尝试if(item[i]!== 0)但它不起作用。

的Ajax:

$(document).ready(function(){
  $.ajax({
    url: "pagination.php",
    type: "POST",
    dataType: "json",
    success:function(data) {  
      var item_html = "";
      console.log(data[0]);
      item_html += '<h3>'+data[0].larger_than_1+'</h3>';  
      $.each(data,function(index,item)
      {
        if(item[index]!== 0)
        {
          item_html += '<p>'+item.kal+'</p>';
        }

      });
      $('#area').append(item_html);
    }

  });
});

2 个答案:

答案 0 :(得分:3)

在if语句中将item[i]更改为i

jsFiddle

答案 1 :(得分:1)

您需要确定需要排除的数据。但是当它作为第一个值出现时,您可以简单地使用索引来过滤掉所需的数据。即if(i!= 0)

var data = [{"larger_than_1":null,"current_page_no":110,"otherpageno":"100,101,102,103,104,105,106,107,108,109,111,112,113,114,115,116,117,118","current_not_equal_total":"true","nextpage":111,"website":"www.google.com"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"}];
var item_html ="";
jQuery.each(data, function(i, item) {
  if(i!= 0)
  {
     item_html += '<p style="margin:5px;background:beige">'+item.kal+'</p>';
  }
  $('#area').append(item_html);
});

<强> Working Demo