2017-10-06 37 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