Dojo请求无法正常运行

时间:2014-05-05 11:48:26

标签: javascript dojo

我有一个 div 标记,它有一个触发dojo XHR请求的OnClick事件。

我的问题是它不会进入 .then(lang.hitch(...))部分,除非我在 firebug中使用断点

createTS : function(){
        var container = document.createElement("div");
        console.log("Hallo World");
        xhr("getoptions.php?database=cb_content.sqlite&order=read").then(lang.hitch(this,function(result){console.og("test");this.temp = result.toString().split(";");}));
        var container = document.createElement("div");
        for(var i = 0; i< this.temp.length; i++){
                var span = document.createElement("span");
                span.setAttribute("id",this.temp[i]);
                span.innerHTML = this.temp[i];
                //on(dom.byId(this.temp[i]),"click",this.foo(span.innerHTML));
                span.setAttribute("class","apus_span_item");
                span.setAttribute("onclick","fptr('"+span.innerHTML+"');");
                container.appendChild(span);
                container.appendChild(document.createElement("br"));                            
        }
        console.log("row before return");
        return '<div>'+container.innerHTML+'</div>';
        //return this.templateString2

    },

控制台告诉我“Hallo World”然后它告诉我发出GET请求,然后控制台告诉我“返回前的行”。但是“测试”将不会被写入。

当我打破分数时,它会告诉我测试。

任何人都有答案为什么它不会进入.then?

问候

1 个答案:

答案 0 :(得分:1)

除了您的代码有console.og()之类的错误而不是console.log()之外,您的设置将无法正常运行。

您尝试在同步代码(this.temp)内使用由异步请求(XHR请求是什么)设置的值。

因此,创建HTML(for循环)的代码很可能正在执行 BEFORE XHR请求已完成,因此,{ {1}}已初始化。 它在使用断点时起作用的原因是因为您要在XHR完成之前延迟HTML创建代码(因为您设置了断点)。

这里有两个解决方案。第一种方法是将this.temp选项设置为sync,将XHR请求转换为同步请求。有关详细信息,请查看reference guideAPI documentation

另一种解决方案是确保只在异步请求完成时才执行创建HTML的代码。你可以通过在回调中移动所有依赖true的代码(this._temp部分内的函数)来实现这一点。

但是,如果您需要从回调中返回一些内容,则必须使用deferreds

相关问题