After an AJAX request, sometimes my application may return an empty object, like:
var a = ({});
How can I check if that's the case?
After an AJAX request, sometimes my application may return an empty object, like:
var a = ({});
How can I check if that's the case?
There's no easy way to do this. You'll have to loop over the properties explicitly:
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
1) Just a workaround. Can your server generate some special property in case of no data? For example:
var a = {empty:true}
;
Then you can easily check it in your AJAX callback code.
2) Another way to check it:
if (a.toSource() === "({})") // then `a` is empty
EDIT: If you use any JSON library (f.e. JSON.js) then you may try JSON.encode() function and test the result against empty value string.
In addition to Thevs answer:
var o = {};
alert($.toJSON(o)=='{}'); // true
var o = {a:1};
alert($.toJSON(o)=='{}'); // false
it's jquery + jquery.json
you must be binding this json to some dom element inspite of checking json best way is to make the the binding function handle such data
For those of you who have the same problem but uses jQuery, you can use jQuery.isEmptyObject.
How about:
if (a.length != undefined) {
// a is good, go ahead
}
This works for me.
Here is another way:
a ={};
var b= {
x: function() { return 'x' }
}
function isNotEmpty(obj) {
return (obj.__count__);
}
alert(isNotEmpty(a));
alert(isNotEmpty(b));
The aim of this function is to detect properties directly on obj.Zero(0) indicates no properties
it's very simple
if is json, i always contains '{}'
so you should write :
"data" is string Json as : {'name':'phucvh', 'age':'21'}
if (data.charAt(0) == '{')
{
alert('is Json');
}