'undefined' printing after javascript function call
My script is loading some data from an XML file and printing a table with it.
function draw_schedule() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","schedule.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.write("<table width='100%' border='1'>");
var x=xmlDoc.getElementsByTagName("day");
for (i=0;i<x.length;i++) {// number of days
document.write("<tr><th colspan='2'>");
document.write(x[i].getElementsByTagName("date")[0].childNodes[0].nodeValue);// the date for each day
document.write("</th></tr>");
var y=x[i].getElementsByTagName("session");// daily sessions
for (j=0;j<y.length;j++) {
docu开发者_运维问答ment.write("<tr><td>");
document.write(x[i].getElementsByTagName("title")[j].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("time")[j].childNodes[0].nodeValue);
document.write("</td></tr>");
}
}
document.write("</table>");
}
If I call the function (separate file) from the HTML file, it prints the table and afterward prints 'undefined'. If I alternatively embed the script in the HTML, it prints the table without printing 'undefined'. I can't figure-out why having the script in a separate file would change its behaviour. I would love for someone with more wisdom than I to explain. Thanks!
draw_schedule()
returns no value (undefined
). You're possibly calling the function with document.write:
document.write(draw_schedule());
draw_schedule()
returns undefined
in this case, and the result would look like this:
document.write(undefined);
Do your document.write
inside this:
xmlhttp.open("GET", "schedule.xml", false);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
var result = xmlhttp.responseXML;
// do your document.write
}
}
}
精彩评论