I am trying to read a XML using ajax request in jquery. Below is the code,it’s working fine in IE but when I run this on Chrome i am facing this error
Uncaught TypeError: Cannot call method ‘hasChildNodes’ of undefined
$.ajax({
type: "GET",
url: "tree1.xml",
dataType:"xml",
success: function(xml){
root=xml.documentElement;
childs=root.childNodes;
for(var i=0;i<childs.length;i++){
z=childs[i].childNodes;
adChilds(z,childs,oNode);
function adChilds(a,b,c){
if(a[i].hasChildNodes()){
adNode(b[i].nodeName,c);
var oNode_ch=oNode1;
for(var j=0;j<a.length;j++){
child1=a[j].childNodes;
adNode(child1[0].nodeValue,oNode_ch);
}
}
else{adNode(a[0].nodeValue,oNode);}
}
}
error is pointing at this line.
if(a[i].hasChildNodes()){
Can anyone suggest me where am I going wrong.
Thanks in advance!
You’re doing this:
then, in the first line of
adChilds(z,childs,oNode);, you’re doing this:But,
iisn’t an index into the children ofa. It’s an index into the parent’s of a’s children. Thus, if the parent ofadoesn’t have the same number of children asahas children, you will go out of index.I don’t know exactly what you’re trying to accomplish in adChilds() so I’m not sure what fix to suggest, but I presume you that if you want to deal with the children of
a, you should get the number of children ofaand make sure you only access the number that actually existSome coding suggestions:
I’d strongly suggest you use real variable names. Names like
a,b,candzfor intermediate variables are cryptic and make your code hard to read.All local variables should be preceded with
varat first definition (or defined at the top of the function), otherwise they become global variables which is asking for trouble, especially with asynchronous callback functions.When you see errors that aren’t obvious to you upon first inspection of your code, then set a breakpoint in your favorite debugger and step through the code and examine the state of the variables to see exactly why you’re getting the error. If you don’t know how to use a debugger, learn. They are built into most browsers, easy and absolutely essential to efficient debugging.