2012-06-22 22 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 
    }); 
}