Javascript Dojo从服务器获取数据,并使用xhrGet存储在变量中
我有以下功能:Javascript Dojo从服务器获取数据,并使用xhrGet存储在变量中,javascript,dojo,Javascript,Dojo,我有以下功能: loadMsgBody: function (id) { return dojo.xhrGet({ url: "myurl", handleAs: "text", content: { id: id }, load: function (response) { return response; }, error:
loadMsgBody: function (id) {
return dojo.xhrGet({
url: "myurl",
handleAs: "text",
content: {
id: id
},
load: function (response) {
return response;
},
error: function (response) {
alert(response);
}
});
}
loadMsgBody: function (id, callback) {
return dojo.xhrGet({
url: "myurl",
handleAs: "text",
content: {
id: id
},
load: function (response) {
if(callback) {
callback(response);
}
},
error: function (response) {
alert(response);
}
});
}
并称之为:
var text = "";
this.loadMsgBody(this.msgId).then(function (response) {
text = response;
});
现在我希望得到函数的返回值,但是我得到的却是文本的空值。然而,在Firebug中,我确实看到了来自服务器的具有正确值的响应。我已搜索并找到以下链接:
以及:
但是我仍然不能用上面的代码获取和存储数据。我不想在xhrGet调用中进行操作,我想检索数据并使用它,因为它将被多次使用
我有什么遗漏吗?试试这个:
loadMsgBody: function (id, callback) {
return dojo.xhrGet({
url: "myurl",
handleAs: "text",
content: {
id: id
},
load: function (response) {
callback.apply(null,[response]);
},
error: function (response) {
alert(response);
}
});
}
然后:
Dojo的XHR方法返回类的实例,因为它们是异步的。这意味着函数在响应值可用之前返回。为了处理异步响应的结果,您需要等待它返回。Dojo使用统一的API(延迟)公开了这一点。
dojo/Deferred
类的实例有一个方法then
。then
方法将函数作为参数。该函数将在延迟问题解决后执行(在本例中,当请求完成时)
我会尝试更改您的
加载
函数以调用您的回调
函数:
loadMsgBody: function (id) {
return dojo.xhrGet({
url: "myurl",
handleAs: "text",
content: {
id: id
},
load: function (response) {
return response;
},
error: function (response) {
alert(response);
}
});
}
loadMsgBody: function (id, callback) {
return dojo.xhrGet({
url: "myurl",
handleAs: "text",
content: {
id: id
},
load: function (response) {
if(callback) {
callback(response);
}
},
error: function (response) {
alert(response);
}
});
}
当您调用
var myData=this.loadMsgBody(this.msgId)时,Firebug会得到什么代码>?您能否在函数回调中为设置断点,然后
并注意分配了什么文本
?我得到[object]
。但是在firebug中,我看到了来自服务器的预期数据的响应。在load
回调中response
的值是多少?看起来某个对象正在转换为字符串,可能这不是您想要的。我不确定您是否应该实际从load
返回任何内容。在load回调中,数据与预期的一样。这将返回文本的空数据,但响应与预期的数据一致。我不知道您在哪里使用“text”变量?您需要确保在asynchorize ajax返回数据后使用它,请参阅我的更新代码。这就是使用它的目的,但即使这样也不能用于赋值。您可以在then函数中获取值,但即使您分配它,也会得到空数据。我感觉您可能会误解“then”,即使您使用then,它仍然是异步的。我在代码中添加了更多内容以使其更清晰。