37
$.getJSON(url, function(json) {
  var output = '';
  $.each(json, function(i,d) {

    if(d.DESCRIPTION == 'null'){ 
      console.log("Its empty");
    }
    var description = d.DESCRIPTION;
    output += '<tr><td>'+d.NAME+'</td><td>'+'<tr><td>'+d.DESCRIPTION+'</td><td>';
  });
});

我尝试添加

if(d.DESCRIPTION == 'null'){ console.log("Its empty"); 

检查返回的对象是否为空,但它不起作用。

有人可以向我解释这有什么问题吗?

4

5 回答 5

74

下面的代码(已经提供了jQuery.isEmptyObject(anyObject)函数)工作得很好,无需自己编写。

   // works for any Object Including JSON(key value pair) or Array.
  //  var arr = [];
  //  var jsonObj = {};
    if (jQuery.isEmptyObject(anyObjectIncludingJSON))
    {
       console.log("Empty Object");
    }
于 2013-11-28T09:38:03.020 回答
60

只需测试数组是否为空。

$.getJSON(url,function(json){
    if ( json.length == 0 ) {
        console.log("NO DATA!")
    }
});
于 2013-01-15T20:11:40.770 回答
7
if (!json[0]) alert("JSON empty");
于 2014-05-27T17:02:14.780 回答
-1

您可以使用 $.isEmptyObject(json)

https://api.jquery.com/jQuery.isEmptyObject

于 2018-03-12T03:27:47.047 回答
-3
$.getJSON(url,function(json){
if ( json.length == 0 ) 
{
console.log("NO !")
}
});
于 2015-08-20T10:51:46.540 回答