Dojo 从服务器获取数据并使用 xhrGet 存储在变量中
Dojo Get data from server and store in a variable using xhrGet
我有以下函数:
loadMsgBody: function (id) {
return dojo.xhrGet({
url: "myurl",
handleAs: "text",
content: {
id: id
},
load: function (response) {
return response;
},
error: function (response) {
alert(response);
}
});
}
并称其为:
var text = "";
this.loadMsgBody(this.msgId).then(function (response) {
text = response;
});
现在我希望获得函数的返回值,但相反,我得到了文本的空值。但是,在Firebug中,我确实看到了来自服务器的具有正确值的响应。我已经搜索并找到了这些链接:DOJO xhr获取如何使用返回的json对象?和:使用挂钩/延迟与 xhrGet 请求但是我仍然无法使用上述代码获取和存储数据。我不想在 xhrGet 调用中进行操作,我想检索数据并使用,因为它将被多次使用。
我缺少什么吗?
Dojo 的 XHR 方法返回类 dojo/Deferred 的实例,因为它们是异步的。 这意味着函数在响应值可用之前返回。 为了处理异步响应的结果,您需要等待它返回。 Dojo 使用统一的 API Deferreds 公开这一点。 dojo/Deferred
类的实例具有方法 then
。 then
方法将函数作为参数。 该函数将在解析延迟后执行(在本例中为请求完成时)。
var deferred = loadMsgBody();
deferred.then(function(response){
//work with response
});
我会尝试更改您的load
函数以唤起您的callback
函数:
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);
}
});
}
试试这个:
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);
}
});
}
然后:
var text = "";
this.loadMsgBody(this.msgId, function (response) {
text = response;
console.log("text:",text); // this will show your return data
});
console.log("text:",text); // this will show empty data because ajax call is asynchrize, at this time , data not return yet.
setTimeout(function(){
console.log("text:",text); // this will show your return data again because ajax call should have finished after 30000 ms
},30000)
相关文章:
- 将作用域存储在JSON中
- 使用javascript存储变量的最安全方式
- 当图像转换为本地存储的DataURL时,EXIF被删除
- 如何在chrome扩展中存储数据/结果,以及如何使用setTimeout使其只被调用一次
- 如何有效地将游戏数据存储在URL查询字符串中
- Ember.js-接口状态应该存储在哪里
- 如何解雇“;铁局部存储负载”;事件
- 本地存储中的字符串到字节数组转换
- 从jQuery调用存储在Variable中的函数
- 推荐在JavaScript中执行存储为字符串的函数,而不是使用eval
- 通过另一个php应用程序将我的项目推送到Github存储库中
- 将数据存储在javascript数组中以供进一步使用
- 在页面卸载时写入HTML5 FileSystem API存储
- 加载存储在IndexedDB中的HTML页面
- 在字符串中查找所有图像 src URL 并存储在数组中
- 如何从C#代码背后调用本地存储的javascript函数
- 在ListView中添加JSON数组中存储的图像-ReactNative
- 将数据存储到元素中
- 使用ajax下载与存储名称不同名称的文件
- Dojo 从服务器获取数据并使用 xhrGet 存储在变量中