简体   繁体   中英

XMLHttpRequest not working

The following code I am using to dynamically update the TextArea element in my HTML every 2 seconds without reloading the page. However, the alert(request.readystate) is returning undefined instead of a number 1-4. When I tried if(request) alert("Request object") it alerts the user "Request object" as expected. I have no clue why this isn't working and I have been trying to figure this out for hours!

My code:

<script type="text/javascript">

    function init(){
      var url="http://www.suchandsuch.net/ChatBowl/text.txt";
      var request= new XMLHttpRequest();
      request.open("POST",url,true);
      alert(request.readystate);
      request.onload= function(){
        if (request.readystate ==4 && request.status == 200){
          document.getElementById('textarea').innerHTML=request.responseText;
        }  
      }
        request.send(null);

     }


    var int=self. setInterval('init()', 2000);

  </script> 

I appreciated any help.

JavaScript is case sensitive and you typed the readyState wrong:

readyState not readystate

MSDN docs

And the callback function should be assigned to onreadystatechange :

var url="http://www.suchandsuch.net/ChatBowl/text.txt";
var request= new XMLHttpRequest();
request.onreadystatechange = function(){
    alert(request.readyState + " " + request.status);
    if (request.readyState ==4 && request.status == 200)
          document.getElementById('textarea').innerHTML=request.responseText;
    };

request.open("POST", url, true);
alert(request.readyState);  

request.send();

maybe instead of

request.onload= function(){

try

request.onreadystatechange = function(){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM