Javascript INVALID_STATE_ERR:DOM 异常 11

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2357430/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:55:18  来源:igfitidea点击:

INVALID_STATE_ERR: DOM Exception 11

javascriptajaxxmlhttprequest

提问by Andres

I'm developing a simple auxiliary class to send requests using XmlHttpRequest (code below). But I cant make it work. At google chrome, for example, I get the error INVALID_STATE_ERR: DOM Exception 11and at the other browsers I get a status == 0.

我正在开发一个简单的辅助类来使用 XmlHttpRequest(下面的代码)发送请求。但我不能让它工作。例如,在 google chrome 上,我收到错误消息,INVALID_STATE_ERR: DOM Exception 11而在其他浏览器上,我收到 status == 0。

//@method XRequest: Object constructor. As this implements a singleton, the object can't be created calling the constructor, GetInstance should be called instead
function XRequest() {
    this.XHR = XRequest.CreateXHR();
}
XRequest.instance = null;

//@method static GetInstance: Creates a singleton object of type XRequest. Should be called whenever an object of that type is required.
//@return: an instance of a XRequest object
XRequest.GetInstance = function() {
    if(XRequest.instance == null) {
        XRequest.instance = new XRequest();
    }
    return XRequest.instance;
}

//@method static CreateXHR: Implments a basic factory method for creating a XMLHttpRequest object
//@return: XMLHttp object or null
XRequest.CreateXHR = function() {
    var xhr = null;
    var factory = [
        function() { return new XMLHttpRequest(); },
        function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
        function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
    ];

    for(var i = 0; i < factory.length; ++i) {
        var f = factory[i];
        xhr = f();
        if(xhr) return xhr;
    }
    return null;
}

XRequest.prototype.SetRequestHeader = function(name, value) {
    if(this.XHR) {
        this.XHR.setRequestHeader(name, value);
    }
}

XRequest.prototype.SendRequest = function(args) {
    var async = true;
    var type = "";
    var url = "";
    var username = "";
    var password = "";
    var body = null;
    var success = null; 
    var failure = null;

    for(e in args) {
        switch(e) {
            case "async":
                async = args[e];
                break;
            case "type":
                type = args[e];
                break;
            case "success":
                success = args[e];
                break;
            case "failure":
                failure = args[e];
                break;
            case "url":
                url = args[e];
                break;
            case "username":
                username = args[e];
                break;
            case "password":
                password = args[e];
                break;
            case "body":
                body = args[e];
            break;
            case "setHeader":
                var h = args[e].split(":");
                if(h.length == 2) {
                    this.SetRequestHeader(h[0], h[1]);
                }
                break;
        }
    }

    var that = this;
    this.XHR.onreadystatechange = function() {
        alert("readyState == " + that.XHR.readyState + "  status == " + that.XHR.status);
        if(that.XHR.readyState == 4) {
            if(that.XHR.status == 200 || that.XHR.status == 0) {
                if(success) success(that.XHR);
            } else {
                if(failure) failure();
            }
        }
    };
    this.XHR.open(type, url, async, username, password);
    this.XHR.send(body);
}

Example of usage:

用法示例:

<script language="javascript">
    function onLoad() {
        var x = XRequest.GetInstance();
        x.SendRequest({type:"GET",
            setHeader:"Accept:text/html, image/png, image/*, */*",
            url: "http://your_server.com/getData?param1=test",
            success:onSuccess, failure:onFail
        });
    }

    function onSuccess(obj) {
        alert("OK");                
    }

    function onFail() {
        alert("Not at this time!");
    }
</script>

采纳答案by Justin Johnson

Regardless, you can simplify your SendRequestmethod by creating a mixin instead of using a giant switch.

无论如何,您可以SendRequest通过创建一个 mixin 而不是使用一个巨大的switch.

XRequest.prototype.SendRequest = function(params) {
    var defaultParams = {
        async:    true,
        type:     "",
        url:      "",
        username: "",
        password: "",
        body:     null,
        success:  null,
        failure:  null
    };

    for ( var i in defaultParams ) {
        if ( defaultParams.hasOwnProperty(i) && typeof params[i] == "undefined" ) {
            params[i] = defaultParams[i];
        }
    }

    var that = this;
    this.XHR.onreadystatechange = function() {
        if ( that.XHR.readyState == 4 ) {
            if ( that.XHR.status == 200 || that.XHR.status == 0 ) {
                if ( params.success ) {
                    params.success(that.XHR);
                }
            } else {
                if ( params.failure ) {
                    params.failure();
                }
            }
        }
    };

    this.XHR.open(
        params.type, parms.url, params.async, params.username, params.password
    );

    // It doesn't make sense to have a for/switch here when you're only handling
    // one case
    if ( params.setHeader ) {
        var h = params.setHeader.split(":");
        if ( h.length == 2) {
            this.SetRequestHeader(h[0], h[1]);
        }
    }

    this.XHR.send(params.body);
};

Also be careful: your existing for..inloops have two distinct problems:

还要小心:您现有的for..in循环有两个不同的问题:

  1. You're not using varand causing a global to be created: for (e in args)should be for (var e in args)
  2. Whenever you use for..in, you should always check to make sure that each key is a direct member of the object, and not something inherited inadvertently through prototype
  1. 您没有使用var并导致创建全局:for (e in args)应该是for (var e in args)
  2. 无论何时使用for..in,都应该始终检查以确保每个键都是对象的直接成员,而不是通过原型无意中继承的东西

.

.

for ( var i in obj ) {
    if ( obj.hasOwnProperty(i) ) {
        // do stuff here
    }
}

回答by ukostin

Problem in this ajax library.

这个 ajax 库中的问题。

XHR.setRequestHeader()must be called after XHR.open().

XHR.setRequestHeader()必须在 之后调用XHR.open()

// @method XRequest: Object constructor. As this implements a singleton, the object can't be created calling the constructor, GetInstance should be called instead
function XRequest()
{
    this.XHR = XRequest.CreateXHR();
}

XRequest.instance = null;


// @method static GetInstance: Creates a singleton object of type XRequest. Should be called whenever an object of that type is required.
// @return: an instance of a XRequest object
XRequest.GetInstance = function()
{
    if(XRequest.instance == null)
    {
        XRequest.instance = new XRequest();
    }

    return XRequest.instance;
}

// @method static CreateXHR: Implments a basic factory method for creating a XMLHttpRequest object
// @return: XMLHttp object or null
XRequest.CreateXHR = function()
{
    var xhr = null;
    var factory = [
                    function() { return new XMLHttpRequest(); },
                    function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
                    function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
                ];

    for(var i = 0; i < factory.length; ++i)
    {
        var f = factory[i];
        xhr = f();
        if(xhr)
            return xhr;
    }

    return null;
}

XRequest.prototype.SetRequestHeader = function(name, value)
{
    if(this.XHR)
    {
        //alert(name+'|||'+value);
        this.XHR.setRequestHeader(name, value);
    }
}

XRequest.prototype.SendRequest = function(args)
{
    var async = true;
    var type = "";
    var url = "";
    var username = "";
    var password = "";
    var body = null;
    var success = null; 
    var failure = null;

    for(e in args)
    {
        switch(e)
        {
            case "async":
                async = args[e];
                break;

            case "type":
                type = args[e];
                break;

            case "success":
                success = args[e];
                break;
            case "failure":
                failure = args[e];
                break;

            case "url":
                url = args[e];
                break;

            case "username":
                username = args[e];
                break;

            case "password":
                password = args[e];
                break;

            case "body":
                body = args[e];
                break;
        }
    }

    var that = this;
    this.XHR.onreadystatechange = function()
        {
            alert("readyState == " + that.XHR.readyState + "  status == " + that.XHR.status);
            if(that.XHR.readyState == 4)
            {
                if(that.XHR.status == 200 || that.XHR.status == 0)
                {
                    if(success)
                        success(that.XHR);
                }
                else
                {
                    if(failure)
                        failure();
                }
            }
        };

    this.XHR.open(type, url, async, username, password);
    for(e in args)
    {
        switch(e)
        {
            case "setHeader":
                var h = args[e].split(":");             
                if(h.length == 2)
                {
                    this.SetRequestHeader(h[0], h[1]);
                }
                break;
        }
    }
    this.XHR.send(body);
}

回答by Dave Lampert

Usually this error occurs with the XMLHttpRequest when you call the open method with async = true, or you leave the async parameter undefined so it defaults to asynchronous, and then you access the status or responseText properties. Those properties are only available after you do a synchronous call, or on the readyState becoming ready (once the asynchronous call responds). I suggest you first try with async = false, and then switch to it being true and use the onReadyStateChange.

通常,当您使用 async = true 调用 open 方法时,XMLHttpRequest 会发生此错误,或者您未定义 async 参数以使其默认为异步,然后您访问 status 或 responseText 属性。这些属性仅在您执行同步调用后或在 readyState 准备就绪(异步调用响应后)时才可用。我建议您首先尝试使用 async = false,然后切换为 true 并使用 onReadyStateChange。

回答by Temperage

In my case the error occurred when i tried to access xhr.statusTextwithin the xhr.onreadystatechangemethod, however retrieving xhr.readyStatewent just fine.

在我的情况下,当我尝试xhr.statusTextxhr.onreadystatechange方法中访问时发生了错误,但是检索xhr.readyState进行得很好。