javascript XMLHttpRequest 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9148202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XMLHttpRequest not working
提问by moesef
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!
我使用以下代码每 2 秒动态更新 HTML 中的 TextArea 元素,而无需重新加载页面。但是,alert(request.readystate)
返回的是 undefined 而不是数字 1-4。当我尝试时,if(request) alert("Request object")
它会按预期提醒用户“请求对象”。我不知道为什么这不起作用,我一直在努力解决这个问题好几个小时!
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.
我很感激任何帮助。
回答by gdoron is supporting Monica
JavaScript is case sensitive and you typed the readyState wrong:
JavaScript 区分大小写,您输入的 readyState 错误:
readyStatenot readystate
readyState的不readyState的
And the callback function should be assigned to onreadystatechange
:
并且回调函数应该分配给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(); ? ? ?
request.send(); ? ? ?
回答by Mikey G
maybe instead of
也许而不是
request.onload= function(){
try
尝试
request.onreadystatechange = function(){