2010-12-04 84 views
1

我的腳本正在從XML文件加載一些數據並用它打印一張表。'undefined'在javascript函數調用後打印

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++) { 
      document.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>"); 
} 

如果我從HTML文件中調用函數(單獨文件),它會打印表格,然後打印'undefined'。如果我將腳本嵌入到HTML中,它將打印表格而不打印「未定義」。我無法弄清楚爲什麼在一個單獨的文件中腳本會改變它的行爲。我會喜歡比我更聰明的人解釋。謝謝!

+0

你完全確定使用`文件撰寫()`是你想要做什麼?由於很多原因,這是構建頁面內容的一個非常不受歡迎的方式。 – Pointy 2010-12-04 22:10:42

回答

1

draw_schedule()沒有返回值(undefined)。你可能調用該函數與文件撰寫:

document.write(draw_schedule()); 

draw_schedule()回報undefined在這種情況下,結果是這樣的:

document.write(undefined); 
+0

謝謝,這很有幫助。我真的不知道爲什麼我用document.write調用函數。有時候這些東西只需要另一套新鮮的眼睛! – steve 2010-12-09 01:49:33

1

做你document.write這裏面:

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 
     } 
    } 
}