2012-12-20 85 views
2

Im新手到AJAX並試圖運行下面這段代碼,但它不工作... Ajax_info.txt文件位於我的本地驅動器。AJAX代碼不能按預期工作

<!DOCTYPE html> 
<html> 
<head> 
<script> 
function loadXMLDoc() 
{ 
var xmlhttp; 
if (window.XMLHttpRequest) 
    {// code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
    } 
else 
    {// code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
xmlhttp.onreadystatechange=function() 
    { 
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText; 
    } 
    } 
xmlhttp.open("GET","c:/python27/ajax_info.txt",true); 
xmlhttp.send(); 
} 
</script> 
</head> 
<body> 

<div id="myDiv"><h2>Let AJAX change this text</h2></div> 
<button type="button" onclick="loadXMLDoc()">Change Content</button> 

</body> 
</html> 
+0

你可能想看看http://stackoverflow.com/questions/7683596/xmlhttprequest-for-local-files雖然如果你正在學習AJAX,你可能會想使用本地Web服務器並從它加載文件而不是文件系統。 – tvanfosson

+0

如果以下答案中的任何一個提出瞭解決方案,請點擊答案旁邊的複選標記以接受答案。這將有助於未來用戶搜索相同問題的答案。謝謝。 – SnareChops

回答

0

我有同樣的問題。我刪除了if (xmlhttp.readyState==4 && xmlhttp.status==200),它效果很好。

+0

它不能正常工作。每次運行時,我都會彈出一個窗口,聲明「IE限制此網頁運行腳本或ActiveX控件」 – user1050619

+0

好吧,我會嘗試爲您調試它。給我幾個。還請檢查您的瀏覽器是否禁用或禁用了ActiveX。 – SnareChops

+0

我的測試在Firefox中運行良好,我使用Mac,所以很不幸我無法爲您測試IE。 – SnareChops

0

通常,由於安全問題,瀏覽器不會打開本地文件。根據瀏覽器的不同,如果引用的HTML文件也是在本地加載的,我認爲它可能會打開它,因爲從技術上講,它們將位於同一個域中。通常,在使用AJAX時,您將使用Web服務器上的文件(即使Web服務器是本地託管的)。無論如何,如果確實有效,您將從本地文件中收到狀態0,狀態200。狀態200是一種HTTP協議狀態,因爲它不是通過HTTP加載的,所以不會爲本地文件返回。

0

請參閱該代碼並運行 你得給參數這樣

xmlhttp.open("GET","?c:/python27/ajax_info.txt",true); 

,告訴我你想要在你的div來顯示什麼

   <!DOCTYPE html> 
      <html> 
      <head> 
      <script> 
      function loadXMLDoc() 
      { 

      var xmlhttp; 
      if (window.XMLHttpRequest) 
       {// code for IE7+, Firefox, Chrome, Opera, Safari 
       xmlhttp=new XMLHttpRequest(); 
       } 
      else 
       {// code for IE6, IE5 
       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
       } 
      xmlhttp.onreadystatechange=function() 
       { 
       if (xmlhttp.readyState==4 && xmlhttp.status==200) 
       { 

       var str = xmlhttp.responseText 
       alert(str) 
       document.getElementById("myDiv").innerHTML="change"; 
       } 
       } 
      xmlhttp.open("GET","?c:/python27/ajax_info.txt",true); 
      xmlhttp.send(null); 
      } 
      </script> 
      </head> 
      <body> 


      <button type="button" onclick="loadXMLDoc()">Change Content</button> 
      <div id="myDiv" >Let AJAX change this text</div> 
      </body> 
      </html>