以下代码用于每2秒动态更新HTML中的TextArea元素,而无需重新加载页面。但是,alert(request.readystate)
返回undefined而不是1-4。当我尝试if(request) alert("Request object")
时,它会按预期警告用户“请求对象”。我不知道为什么这不起作用,我一直试图弄清楚这几个小时!
我的代码:
<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>
我感激不尽。
答案 0 :(得分:3)
JavaScript区分大小写,您键入readyState错误:
readyState 不是就绪状态
应将回调函数分配给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();
答案 1 :(得分:0)
也许不是
request.onload= function(){
试
request.onreadystatechange = function(){