how to manage the ajax response in Dojo
Ok, this may be a dumb question, but I can't find a way to solve my problem. I have this function:
function getActivityObj(sysId, date) {
var activityObj = dojo.xhrGet({
url: 'calendar/display-subactivities',
content: {'sysId': sysId, 'date': date},
handleAs: 'json',
load: function(result) {
console.log(result);
开发者_开发问答 },
error: function(){
alert("error");
}
});
var ajaxResponse = activityObj.ioArgs.xhr.response;
return ajaxResponse;
}
The problem is that my ajaxResponse variable is always empty, but if in firebug, the xhr object the response property is not empty. I will use the ajax response in several places in my code so what am I doing wrong or what would be a better way to call the ajax response? Thank you. (Sorry for my bad english)
I suspect the ajaxResponse
variable is empty when you call it because the xhrGet()
call is made asynchronously, and the result is not actually available yet when you set ajaxResponse
and return it from your function.
By the time you view it in firebug, the XHR response has completed but it just isn't there when your code executes.
xhrGet()
returns a dojo.Deferred
object. You can use that to add a callback function for when it actually completes:
function getActivityObj(sysId, date) {
var activityObj = dojo.xhrGet({
url: 'calendar/display-subactivities',
content: {'sysId': sysId, 'date': date},
handleAs: 'json',
load: function(result) {
console.log(result);
},
error: function(){
alert("error");
}
});
var ajaxResponse;
// activityObj is a Deferred
activityObj.addCallback(function() {
// Use your deferred response
ajaxResponse = activityObj.ioArgs.xrh.response;
// Now inside this function, do whatever you were going to do
// with the xhr return data that you intended to return from
// the wrapping function.
});
}
I am not certain if there's a good way to wrap the xhrGet()
call in a function and attempt to return the response though, since it will always be deferred if called asynchronously.
If it is safe to block further execution until the xhrGet()
call has actually returned data, you can call it synchronously. Then your code as you have it will work without a deferred callback. Instead you would typically do whatever work the returned data was intended for in the xhrGet()
's load()
function.
var activityObj = dojo.xhrGet({
// Call synchronously
sync: true,
url: 'calendar/display- subactivities',
content: {'sysId': sysId, 'date': date},
// etc...
精彩评论