Reputation: 3097
I trying to get some data in json
type with ajax in jQuery, so I wrote this code :
$.ajax({
url: link.attr('href'),
type: 'post',
data: 'post=true',
dataType: 'json',
success: function(data){
if (data.length > 0) {
ldLayer.fadeOut('slow');
}else{
alert('no data');
}
}
});
But when the data
is null
the if
will true and ldLayer.fadeOut('slow');
will run !
UPDATE:
The console.log(data)
result is : [null]
Upvotes: 4
Views: 18425
Reputation: 121998
Simply Check like this
if (data) {
ldLayer.fadeOut('slow');
} else {
alert('no data');
}
Upvotes: 2
Reputation: 115950
You're getting back an array of results. In the problem case you describe, you're getting back an array with a single null
element. An empty array ([]
) has a length of 0, but an array with a single null element ([null]
) has length 1.
In the client, you can check if any of the array's elements are non-null
:
success: function(data){
var foundSomething = false;
for(var i=0; i<data.length; ++i) {
if(data[i] !== null) foundSomething = true;
break;
}
if(foundSomething) {
ldLayer.fadeOut('slow');
}else{
alert('no data');
}
}
However, a much better approach would be to fix your server-side code so it doesn't send back arrays with null
elements. If you don't have control over the server code, however, the client-side solution I've provided above is your best bet.
Upvotes: 4