文件-通过ajax读入div。我想我错过了一些小事
我正在做一些非常简单的事情,但它不起作用......也许我错过了一些东西。
我需要通过 ajax 读取一个文本文件,并将其放入 div 中。我可以通过ajax轻松写入文件,但不能读取。这就是我所拥有的:
function ajaxLoader(url) {
if(document.getElementById) {
var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
}
if(x) {
x.onreadystatechange = function() {
if(x.readyState == 4 && x.status == 200) {
el = document.getElementById('content');
el.innerHTML = x.responseText;
}
}
x.open("GET",url, true);
x.send(null);
}
}
<a class="blocklink" href="#" id="readg" onclick="ajaxLoader('guestBook.txt')">Read The Guestbook</a></p>
<div id="content" style="width:600px;">
我一整天都被困在这个问题上。我可以使用所有相同的代码,并将常规 html 文件输出到 div,但不能输出这个 .txt 文件。 txt 文件具有其所需的所有读写权限。谢谢!
马库斯
I'm doing something very simple, and yet it's not working.. maybe I'm missing something.
I need to read a text file, through ajax, and into a div. I can easily write to the file through ajax, but not read. Here is what I have:
function ajaxLoader(url) {
if(document.getElementById) {
var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
}
if(x) {
x.onreadystatechange = function() {
if(x.readyState == 4 && x.status == 200) {
el = document.getElementById('content');
el.innerHTML = x.responseText;
}
}
x.open("GET",url, true);
x.send(null);
}
}
<a class="blocklink" href="#" id="readg" onclick="ajaxLoader('guestBook.txt')">Read The Guestbook</a></p>
<div id="content" style="width:600px;">
I've been stuck on this all day. I can use all of the same code, and output a regular html file to the div, but not this .txt file. The txt file has all of the read write privileges it needs. Thanks!
Marcus
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试删除该
if(document.getElementById)
您可以提醒您的
.responseText
属性吗?它使用同步模式工作吗?Try to remove that
if(document.getElementById)
Can you alert your
.responseText
property? It works using a synchronous pattern?您的 ajaxLoader 函数应返回 false,以便不会跟踪所单击的链接。
Your ajaxLoader function should return false so that the link that is clicked is not followed.
如果您在本地运行代码,您将获得状态 0 而不是状态 200。要处理这两种情况,您可以使用:
此外,当您单击链接时,将跟随该链接,因为您尚未取消它。由于 href 是“#”,它会转到同一页面的顶部,但仍然会导致问题。 (一个副作用是,当您按下链接时,页面将滚动到顶部。)通过从 click 事件返回 false 来取消链接:
If you are running the code locally, you will get the status 0 instead of status 200. To handle both, you can use:
Also, when you click the link, the link will be followed as you haven't cancelled it. As the href is "#" it will go to the top of same page, but it can still cause problems. (One side effect is that the page will scroll to the top when you press the link.) Cancel the link from being followed by returning false from the click event:
想通了..我从未清除过缓存...缓存再次获胜!
Figured it out.. I never cleared the cache... the CACHE WINS AGAIN!