2012-06-22 23 views
0

我试图使用deferredhitch为了提供我的AJAX请求的回调。我使用下面的代码:使用搭载/推迟xhrGet请求

//Code is executed from this function 
function getContent(){ 
    var def = new dojo.Deferred(); 
    def.then(function(res){ 
    console.lod("DONE"); 
    console.log(res); 
    }, 
    function(err){ 
     console.log("There was a problem..."); 
    }); 
    this.GET("path", def); 
} 

//Then GET is called to perform the AJAX request... 
function GET(path, def){ 
dojo.xhrGet({ 
    url : path, 
    load : dojo.hitch(def,function(res){ 
     this.resolve(res); 
    }), 
    error : dojo.hitch(def, function(err){ 
     this.reject(err) 
    }) 
}) 

}

然而,当我运行此代码我得到this.resolve(res)undefined method错误。我已经打印了this(解析为延迟对象)和res,两者都未定义。为什么我得到这个错误以及如何实现我正在尝试做的事情?

回答

1

ajax方法(xhrGet和xhrPost)在执行时返回延迟对象。有了这个延迟对象,你就可以注册回调和错误回调处理程序时,Ajax请求完成

var deferred = dojo.xhrGet({url:'someUrl'}); 
deferred.then(dojo.hitch(this,this.someCallbackFunction),dojo.hitch(this,this.someErrorFunction)); 

有了这个代码,someCallbackFunction当你的Ajax请求成功返回将被调用,如果有错误的AJAX请求返回,将会调用someErrorFunction

对于你的代码的特定代码块更新这样的:

function getContent(){ 
    var resultFunction = function(res){ 
     console.lod("DONE"); 
     console.log(res); 
    }; 
    var errorFunction = function(err){ 
     console.log("There was a problem..."); 
    }; 
    this.GET("path").then(dojo.hitch(this,resultFunction),dojo.hitch(this,errorFunction); 
} 

//Then GET is called to perform the AJAX request... 
function GET(path){ 
    return dojo.xhrGet({ 
    url : path 
    }); 
}