首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XHR onreadystatechange回调

XHR onreadystatechange回调
EN

Stack Overflow用户
提问于 2014-03-08 10:27:51
回答 1查看 408关注 0票数 0

我编写了一些脚本,但现在我不知道如何向xhr对象的onreadystatechange函数添加回调函数。

这是一些代码。

代码语言:javascript
复制
    function Trace (str){
      alert(str);
    }

    //login durchführen
    var Auth = {
        auth_url : "?evt=Login&mod=_do",
        loggedin : false
    };

    Auth.Init = function(){
        if(!this.loggedin){
            Loader.GetJSON(api.url+this.auth_url+"&username=****&password=*****", true, "Auth.Login");
        }
    }

    Auth.Login = function(object){
        Trace("Auth.Login");
        if(object.user_ok == 200){
            Trace("true!");
        }else{
            Trace("false");
        }
    };

    var Loader = {
      xhr : null
    }

    Loader.GetJSON = function(url, type, fnCallback){

        if (this.xhr != null) {
            try {
                this.xhr.destroy();
                this.xhr = null;
            } catch (e) {
                Trace("Fehler in Loader.Request : " + e);
            }
        }
        this.xhr = new XMLHttpRequest();
        if (this.xhr) {

            if (typeof this.xhr.overrideMimeType == "function") {
                this.xhr.overrideMimeType('application/json');
            }
            //********
            this.xhr.onreadystatechange = function() {
                if (Loader.xhr.readyState == 4 && Loader.xhr.status == 200) {
                    var data = api.ParseJSON(Loader.xhr.responseText);
                    if (typeof data == 'object') {
                        fnCallback (data);
                    }else {
                        Trace(":::: Error in Loader.GetJSON => invalid json");
                    }
                } else if (Loader.xhr.readyState == 4 && Loader.xhr.status != 200) {
                    Trace(":::: Loader.GetJSON Connection error");

                }
            };

            // ******************
            this.xhr.open("GET", url, type);
            this.xhr.send(null);
            // ******************

        } else {
            Trace(":::: Loader.Request Fatal Error");

        }
    };

Auth.Init();

但是这里我得到了一个错误: fnCallback不是一个函数

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-08 10:33:21

因为Auth.Login是一个字符串,而不是一个函数。您需要使用window引用它才能正常工作:

而不是fnCallback(data)

使用window[fnCallback](data)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22268086

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档