Reputation: 6216
I'm trying to grab a dictionary object which is converted to json object in server side, (along with correct content-type header), but for some reason, even though I can access part of the data, other parts don't show up and json object in jquery has length equal to 0.
Here is my jquery call:
$.ajax({
type : "POST",
url : cl._url,
//data : 'text='+text,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType : "json",
error : function(XHR, status, error) {
alert("There was an error processing the request.\n\n"+XHR.responseText);
},
success : function(json){
if (!json.length) {
alert('There are no incorrectly spelled words...'+json[0]+ ' ' + json.length);
} else {
// highlight bad words
}
cl.$container.html(html);
// execute callback function, if any
(callback != undefined) && callback();
}
});
I usually get the alert box with this code, and json[0] prints out 99 as expected. But json.length is "undefined". So in a sense, the json returned is right but my code will not detect it and use it.
When I go directly to my ashx page where my json data is printed on the screen, I get this json object:
{"id":1,"json":[5,10,15,20],"0":"99"}
Just a sample json output. So how come json.length is not 3???
UPDATE: So I changed my asp.net code, from Dictionary to List, and then added the same values. And suddenly, length is functioning now. ?!?!?! So objects don't have lengths in javascript?
Upvotes: 2
Views: 13979
Reputation: 7159
You can convert your object to JSON
using :
var jsonVariable= JSON.stringify(objectVariable);
var jsonVariableLength = jsonVariable.length ;
And print the length :
alert('Length : ' + jsonVariableLength );
Upvotes: 0
Reputation: 943615
Objects don't have a length property unless you give them one. Arrays do, but arrays are created with []
not {}
.
If you want to know how many properties an object has, you have to loop over them and count them:
var count = 0;
for (var foo in bar) {
if (bar.hasOwnProperty(foo) {
count++;
}
}
Upvotes: 8
Reputation: 1342
Best way to debug this is to inspect the response under Firebug console. See if you are even getting back a valid response.
Upvotes: 0