javascript 未捕获的错误:InvalidStateError:DOM Exception 11 with AJAX?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15398571/
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
Uncaught Error: InvalidStateError: DOM Exception 11 with AJAX?
提问by bnynn
I'm running a simple AJAX request:
我正在运行一个简单的 AJAX 请求:
function makePages(num) {
var conn = new XMLHttpRequest();
conn.onreadystatechange = function() {
if (conn.status === 200 && conn.readyState === 4) { //error here
$('#oldPost').before(conn.responseText);
}
else{
return
}
}
conn.open('GET','includes/feedExtra.php?num=' + num);
conn.send();
}
The code runs correctly and the PHP returns the correct content. However, there is an error in Chrome's console:
代码运行正确,PHP 返回正确的内容。但是,Chrome 的控制台中出现错误:
Uncaught Error: InvalidStateError: DOM Exception 11
未捕获的错误:InvalidStateError:DOM 异常 11
it points to this line:
它指向这一行:
if (conn.status === 200 && conn.readyState === 4) {
if (conn.status === 200 && conn.readyState === 4) {
What am I doing wrong?
我究竟做错了什么?
回答by Eric Leschinski
The error:
错误:
Uncaught Error: InvalidStateError: DOM Exception 11
Means you are asking for status in the wrong state. conn.status is not available during readyState of 0 or 1.
意味着您在错误的状态下要求状态。conn.status 在 readyState 为 0 或 1 期间不可用。
Your problem is you are using conn.status when the readyState is 0 and 1.
您的问题是当 readyState 为 0 和 1 时您正在使用 conn.status。
You need to add code to make sure conn.status is not queried in the inappropriate states, like this:
您需要添加代码以确保在不适当的状态下不会查询 conn.status,如下所示:
if(conn.readyState === 4 && conn.status === 200){
Then your code will only query conn.status at the appropriate time.
那么你的代码只会在适当的时候查询 conn.status 。
Ref:
参考:
回答by couzzi
Try this:
试试这个:
conn.open('GET','includes/feedExtra.php?num=' + num, false);
false
makes the request synchronous, true
/ default is asynchronous.
false
使请求同步,true
/默认是异步的。
In your case, it's defaulting to true
, which means the properties in your conditional (conn.status === 200 && conn.readyState === 4)
aren't available yet. They will be until after the call.
在你的情况下,它的默认为true
,这意味着你的条件属性(conn.status === 200 && conn.readyState === 4)
不可尚未。他们将在通话结束后等待。
Hopefully that helps you some.
希望对你有所帮助。
Also, checkout this discussion here.
另外,请在此处查看此讨论。