File-read into div through ajax. I'm missing something small I think
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 privile开发者_StackOverflowges it needs. Thanks!
Marcus
Try to remove that if(document.getElementById)
Can you alert your .responseText
property? It works using a synchronous pattern?
Your ajaxLoader function should return false so that the link that is clicked is not followed.
If you are running the code locally, you will get the status 0 instead of status 200. To handle both, you can use:
if (x.readyState == 4 && (x.status == 0 || x.status == 200))
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:
onclick="ajaxLoader('guestBook.txt');return false;"
Figured it out.. I never cleared the cache... the CACHE WINS AGAIN!
精彩评论