Reputation: 7095
I am trying to use AJAX and XmlHttpRequest to load a text file in web2py:
{{extend 'layout.html'}}
<span id="timer"></span>
<script type="text/javascript">
var count=0;
var counter=setInterval(timer, 250);
var reader = new XMLHttpRequest();
function loadFile() {
reader = new XMLHttpRequest();
reader.open('get', 'wnewfile.txt', true);
reader.onreadystatechange = displayContents;
reader.send(null);
}
function displayContents() {
if(reader.readyState==4 && reader.status==200) {
document.getElementById("timer").innerHTML= reader.responseText ;
} else {
document.getElementById("timer").innerHTML= "status:" + reader.status + " Ready State: " + reader.readyState;
}
}
function timer()
{
loadFile();
}
</script>
{{=BEAUTIFY(response._vars)}}
The result of this is always status:400 (bad request) and readyState:4 (bad request).
I am new to python, AJAX and js and I am wondering if there is any problem on using XmlHttpRequest in web2py and what is the reason I cannot reach the file...
Any thoughts? Thanks
Upvotes: 0
Views: 592
Reputation: 25536
The URL you are passing to .open()
is a relative URL, so it will be added to the URL of the current page, which is most likely not correct. If that file is in the web2py application's static folder, you would need to specify the URL as follows:
reader.open('get', '{{=URL('static', 'wnewfile.txt')}}', true);
Anyway, unless you have a good reason not to, you are probably better off using the web2py ajax()
function, or one of the jQuery Ajax functions (.ajax
or .load
).
Upvotes: 1