2017-10-06 14 views
-2
<div id="new"></div> 
<button id="btn" onclick="changeContent('C:\Users\MarshMellow\Desktop\whatever.txt', newFunc)">Click Here!!</button> 
<script type="text/javascript"> 
function changeContent(url,callFunc) { 
    var xhttp;`declaration' 
    xhttp.onreadystatechange= function() { 
     if(this.readyState == 4 && this.status == 200) { 
      callFunc(this); 
     } 
    }; 
    xhttp.open("GET","C:\Users\MarshMellow\Desktop\whatever.txt",true); 
    xhttp.send(); 
} 
function newFunc(xhttp) {`Function call` 
    document.getElementById("new").innerHTML=xhttp.responseText; 
} 

仍然沒有輸出。看起來像AJAX呼叫無法正常工作。如何使用AJAX調用訪問任何文本或XML文件?

+1

請張貼的代碼,而不是代碼的圖像爲我工作。你也有任何控制檯中的錯誤? – tommyO

+0

也從你的圖像看起來像'callFunc'被調用,但沒有定義。 – tommyO

+0

您的瀏覽器可能不允許通過XHR加載本地文件。 –

回答

0

您似乎正在使用計算機上的靜態文件,如果您想進行ajax調用,則需要服務器發出請求。 嘗試設置一個服務器,並將這些文件放在網站的目錄中,如果你想使用ajax調用如此糟糕。 另一種選擇是使用文件輸入和filereader api

-1

您需要實例化XMLHttpRequest對象。

它使用此文件 https://www.w3schools.com/xml/note.xml

function changeContent(url, callFunc) { 
    var xhttp = new XMLHttpRequest(); // instantiate XMLHttpRequest 
    xhttp.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
     callFunc(this); 
    } 
    }; 
    xhttp.open("GET", url, true); 
    xhttp.send(); 
} 

基本文檔The XMLHttpRequest Object

相關問題