Анонимная функция js с xhrpost dojo не возвращает данные
var cType = function(templateId){
dojo.xhrPost({
url : "/mediation1.0.1/template/getCollectorType",
handleAs : "text",
headers : {"Content-Type":"text/html"},
postData : templateId,
load: function(data){
return data;
}});
};
Когда я вызываю эту функцию с помощью cType(withSomeId), я получаю неопределенное значение. Даже когда я беру локальную переменную и назначаю данные этой переменной, возвращение этой переменной также не помогает.
1 ответ
Решение
Проблема в том, что ваша функция cType ничего не возвращает.
var cType = function(templateId){
dojo.xhrPost({
url : "/mediation1.0.1/template/getCollectorType",
handleAs : "text",
headers : {"Content-Type":"text/html"},
postData : templateId,
load: function(data){
return data;
// this returns from the the load
// function, not the cType function!
}});
// You are not returning anything from the cType function.
};
Вы должны использовать dojo.Deferred
чтобы выполнить то, что вы пытаетесь сделать:
var cType = function(templateId){
var xhrArgs = {
url : "/mediation1.0.1/template/getCollectorType",
handleAs : "text",
headers : {"Content-Type":"text/html"},
postData : templateId
};
return dojo.xhrGet(xhrArgs);
};
var deferred = cType('templateId');
deferred.then(
function(data){
// do something with the data...
},
function(error){
// handle an error calling the server...
}
);
http://dojotoolkit.org/reference-guide/1.7/dojo/xhrGet.html (здесь приведен пример, показывающий метод отсроченного исполнения)
http://dojotoolkit.org/reference-guide/1.7/dojo/xhrPost.html