为什么这段js会抛出DOM异常? [英] why does this piece of js throw a DOM Exception?

查看:35
本文介绍了为什么这段js会抛出DOM异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么这个 fiddle 抛出 ><块引用>

未捕获的错误:InvalidStateError:DOM 异常 11

函数 url(){return '/echo/js/?js=' + 5 + Math.floor(Math.random()*900);}功能投票(完成){var xhr = new XMLHttpRequest();xhr.onreadystatechange = function(){if(xhr.status === 200 && xhr.readyState === 4){var foo = xhr.responseText;完成(parseInt(foo));}};xhr.open('get',url(),false);xhr.send(null);}var button = document.querySelector('#poller');var price = document.querySelector('#price');button.addEventListener('点击', function(){民意调查(功能(数据){price.innerText = 数据;});},错误的);

解决方案

问题是readyState为0/1时状态不可用

您需要在 if 中颠倒顺序.

if(xhr.readyState === 4 && xhr.status === 200){

规范说它应该返回零 "如果状态是 UNSENT 或 OPENED,返回 0 并终止这些步骤.",但出于某种原因,某些浏览器会这样做如果状态未打开或设置了 send() 标志,则会引发InvalidStateError"异常."这就是 setRequestHeader 所做的.此外,您的代码很奇怪,您将它与同步请求一起使用.

所以这里的问题是浏览器没有像规范所说的那样返回零.更改 if 语句中的顺序会阻止浏览器到达该点,因为第一次检查失败.

以及 WebKit 上的错误

I can't figure out why this fiddle throws

Uncaught Error: InvalidStateError: DOM Exception 11

function url(){
 return '/echo/js/?js=' + 5 + Math.floor(Math.random()*900);
}

function poll(done){
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
        if(xhr.status === 200 && xhr.readyState === 4){
            var foo = xhr.responseText;
            done(parseInt(foo));
        }
    };
    xhr.open('get',url(),false);
    xhr.send(null);
}

var button = document.querySelector('#poller');
var price = document.querySelector('#price');

button.addEventListener('click', function(){
    poll(function(data){
        price.innerText = data;
    });
},false);

解决方案

The problem is the status not available when the readyState is 0/1

You need to reverse the order in your if.

if(xhr.readyState === 4 && xhr.status === 200){

The spec says it should return zero "If the state is UNSENT or OPENED, return 0 and terminate these steps.", but for some reason some browsers do this "Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set." which is what setRequestHeader does. Also your code is weird that you would use it with a synchronous request.

So the issue here is the browser is not returning zero like the spec says so. Changing the order in the if statement prevents the browser from reaching that point since the first check fails.

And the bug on WebKit

这篇关于为什么这段js会抛出DOM异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆