使用AJAX读取本地文件

我是AJAX的新手,只想确认一下:如果我所有的代码都放在桌面上的文件夹中,并且正在使用AJAX以HTML格式在div中输出文件内容,是否可以通过AJAX或文件应该必须在服务器上?

我正在第一次测试AJAX功能,并且由于它在.js文件中显示错误“访问被拒绝”而面临问题


慕斯709654
浏览 940回答 3
3回答

小唯快跑啊

出于安全原因,JavaScript对客户端上文件系统的访问受到限制-请考虑是否要(其他人的)JavaScript读取敏感文档。即使在进行实验时,最好使用实际的拓扑,也要从服务器上提供服务,而该服务器将在实际系统中从那里提供服务。设置一个Web服务器(例如Apache)指向您的开发目录确实很容易,因此“服务器”只是您的桌面而已。因此,编辑/测试周期确实很快。

一只名叫tom的猫

我希望可以使用Ajax在本地访问文件,我在mozilla firefox上尝试了该文件并运行良好。我创建了2个文本文件,并在同一个文件夹中移动。这是代码。抱歉,有任何错误。function getXmlHttpRequestObject() {&nbsp; &nbsp; if (window.XMLHttpRequest) {&nbsp; &nbsp; &nbsp; &nbsp; return new XMLHttpRequest(); //Not IE&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; else if(window.ActiveXObject) {&nbsp; &nbsp; &nbsp; &nbsp; return new ActiveXObject("Microsoft.XMLHTTP"); //IE&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; alert("Your browser doesn't support the XmlHttpRequest object.&nbsp; Better upgrade to Firefox.");&nbsp; &nbsp; }}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var receiveReq = getXmlHttpRequestObject();&nbsp; &nbsp; &nbsp;function sayHello(fname) {&nbsp; &nbsp; if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {&nbsp; &nbsp; &nbsp; &nbsp; receiveReq.open("GET", fname, true);&nbsp; &nbsp; &nbsp; &nbsp; receiveReq.onreadystatechange = handleSayHello;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; receiveReq.send(null);&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}function handleSayHello() {&nbsp; &nbsp; if (receiveReq.readyState == 4) {&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById('span_result').innerHTML = receiveReq.responseText;&nbsp; &nbsp; }}Here is the html code<select name="files" onchange="sayHello(this.value)"><option value="">Select a file</option><option value="file.txt">file.txt</option><option value="file2.txt">file2.txt</option><option value="ajax.html">Ajax.html</option></select><br><p>Contents of the file will be displayed below</p><div id="span_result"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript