Ajax的Onreadystatechange返回Uncaught Typeerror

时间:2018-04-27 13:54:34

标签: javascript ajax ajaxform

是ajax的新手,我正在尝试创建一个简单的ajax网页,但我遇到了这个问题

  

未捕获的TypeError:无法设置属性' onreadystatechange'的   window.onload(test.js:4)

未定义

这是我创建的test.js页面代码

window.onload = function(){
'use strict';
var ajax = getXMLHttpRequestObject();
ajax.onreadystatechange = function(){
if(ajax.readyState == 4){
if((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304)){
document.getElementById('output').innerHTML = ajax.responseText;
}else{
document.getElementById('output').innerHTML = 'Error ' + ajax.statusText;
}
}
};
document.getElementById('btn').onclick = function(){
ajax.open('GET', 'resources/test.txt', true);
ajax.send(null);
};
}
function getXMLHttpRequestObject(){
var ajax = null;
if(window.XMLHttpRequest){
ajax = new XMLHttpRequest();
}else if(window.ActiveXObject){
ajax = new ActiveXObject('MSXML2.XMLHTTP.3.0');
} 
}

虽然这是名为test.html的html页面

 <!DOCTYPE html>
 <html>
     <head>
         <title>Ajax test</title>
     </head>
     <body>
         <div><button type="button" id="btn">Run the test</button><br>
             <p id="output"></p>
         </div>
         <script src ="js/test.js"></script>
     </body>
 </html>

与此同时,我试图在XAMPP上运行它

1 个答案:

答案 0 :(得分:1)

我刚刚在两个函数的末尾返回了变量ajax。

&GT;

 window.onload = function(){
>          'use strict';
>          var ajax = getXMLHttpRequestObject();
>          ajax.onreadystatechange = function(){
>              if(ajax.readyState == 4){
>                  if((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304)){
>                      document.getElementById('output').innerHTML = ajax.responseText;
>                  }else{
>                      document.getElementById('output').innerHTML = 'Error ' + ajax.statusText;
>                  }
>              }
>          };
>              document.getElementById('btn').onclick = function(){
>                  ajax.open('GET', 'resources/test.txt', true);
>                  ajax.send(null);
>              };
>              **return ajax;**
>      }
>      function getXMLHttpRequestObject(){
>          var ajax = null;
>          if(window.XMLHttpRequest){
>              ajax =  new XMLHttpRequest();
>          }else if(window.ActiveXObject){
>              ajax = new ActiveXObject('MSXML2.XMLHTTP.3.0');
>          }    
>          **return ajax**
>      }