开发者

JavaScript array from parsing JSON is undefined

开发者 https://www.devze.com 2023-03-09 06:44 出处:网络
So, the gecko thing again, the JSON that im using in this script to populate a listbox is valid according to JSONLint, and im usig code like this to place the parsed data in arrays

So, the gecko thing again, the JSON that im using in this script to populate a listbox is valid according to JSONLint, and im usig code like this to place the parsed data in arrays

pdata = jQuery.parseJSON(data);
ctype = pdata[0];
stype = pdata[1];
lizlist = pdata[2];

now, it gets t one point where I loop through the array ctype (look at the JSON file I linked for reference) using this code

lbt = "";
for(var i in ctype) {
lbt += "<option value=\""+ctype[i].id"\"+>"+ctype[i].type+"</option>"
}

then it ake this code an place it in a listbox on the page. However, this listbox get populated with the开发者_运维百科 value "undefined" and only one "undefined" (there should be three options, one header) for the javascript file im talking about go here the page this is on is "http://texaslizardconnection.com/#newavailable" A little info about this javascript:

pdata[0]~pdata[2] should contain arrays

pdata[2] should conatain more arrays

pdata[0] == pdata["cType"]

pdata[1] == pdata["sType"]

pdata[2] == pdata["lizlist"]


replace your loop with:

for (var i=0;i< ctype.length; i++)

You're looping through every property of the ctype object.


When you are looping over ctype, you forgot to specify to loop over the cType property.

This works:

for(var i in ctype.cType) {
    lbt += "<option value=\""+ctype.cType[i].id+"\">"+ctype.cType[i].type+"</option>";
}


var pdata = jQuery.parseJSON(data);
if (!pdata.cType) {
  alert('fail, cType is null');
} else if (!pdata.sType) {
  alert('fail, sType is null');
} else {
  // cType is an array!
  lbt = "";
  for (var i=0, item; item = pdata.cType[i]; i++) {
    lbt += "<option value=\""+item.id+"\">"+item.type+"</option>";
  }
  // and so on
}
0

精彩评论

暂无评论...
验证码 换一张
取 消