Ajax function only working with alert()

361 Views Asked by At

I'm trying to get AJAX to read a text file(which works) but it will only display the responseText if I have an alert() in the function(which I don't want).

Is there a way to get it to displa the responseText without an alert()? This is my current code.

    <script type="text/javascript"> 
         function load(){
             var txtFile = new XMLHttpRequest();
             txtFile.open("GET", "current.txt", true);
             txtFile.send(null);
             document.write(txtFile.responseText);
         }
    window.onload = load;
    </script>
1

There are 1 best solutions below

1
On

Change the .open method to false so as not use async. If true, assign a callback handler to the onreadystatechange property to determine when the call has completed. Adding a alert was adding a sufficient wait for the file to return so it worked.

txtFile.open("GET", "current.txt", false);

Source: http://msdn.microsoft.com/en-us/library/ms536648(v=vs.85).aspx