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
}
开发者_如何学C 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?
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++;
}
}
Best way to debug this is to inspect the response under Firebug console. See if you are even getting back a valid response.
http://getfirebug.com/
You can convert your object to JSON
using :
var jsonVariable= JSON.stringify(objectVariable);
var jsonVariableLength = jsonVariable.length ;
And print the length :
alert('Length : ' + jsonVariableLength );
精彩评论