Dojo 回调函数中的可变可见性
我使用此函数直接在有用的数据结构中获取查询结果。问题如下:在第一个console.log()调用中,在回调函数内部,存储的_数据变量包含确切的结果,在第二个console.log()调用中,存储的_数据变量看起来没有初始化。建议?? 代码如下:Dojo 回调函数中的可变可见性,dojo,object,return-value,callback,Dojo,Object,Return Value,Callback,我使用此函数直接在有用的数据结构中获取查询结果。问题如下:在第一个console.log()调用中,在回调函数内部,存储的_数据变量包含确切的结果,在第二个console.log()调用中,存储的_数据变量看起来没有初始化。建议?? 代码如下: function dojo_query_mysql(query_string) { //The parameters to pass to xhrPost, the message, and the url to send it to
function dojo_query_mysql(query_string) {
//The parameters to pass to xhrPost, the message, and the url to send it to
//Also, how to handle the return and callbacks.
var stored_data;
var raw_data = new Object;
var xhrArgs = {
url: "query.php",
postData: query_string,
handleAs: "text",
load: function(data) {
raw_data = dojo.fromJson(data);
stored_data = new dojo.data.ItemFileReadStore({data: raw_data});
console.log(stored_data);
},
error: function(error) {
//We'll 404 in the demo, but that's okay. We don't have a 'postIt' service on the
//docs server.
//stored_data = error;
}
}
//Call the asynchronous xhrPost
var deferred = dojo.xhrPost(xhrArgs);
console.log(stored_data);
return stored_data;
}
var xhrArgs = {
url: "query.php",
sync: true, // THIS IS FORCE THE SYNCRONIZATION BETWEEN THE CALLBACK AND THE CODE
postData: query_string,
handleAs: "text",
load: function(data) {
raw_data = dojo.fromJson(data);
stored_data = new dojo.data.ItemFileReadStore({data: raw_data});
console.log(stored_data);
},
error: function(error) {
//We'll 404 in the demo, but that's okay. We don't have a 'postIt' service on the
//docs server.
//stored_data = error;
}
}
我刚刚记住,函数不会等待回调执行结束,因为等待回调结束只需对代码做一点更改:
function dojo_query_mysql(query_string) {
//The parameters to pass to xhrPost, the message, and the url to send it to
//Also, how to handle the return and callbacks.
var stored_data;
var raw_data = new Object;
var xhrArgs = {
url: "query.php",
postData: query_string,
handleAs: "text",
load: function(data) {
raw_data = dojo.fromJson(data);
stored_data = new dojo.data.ItemFileReadStore({data: raw_data});
console.log(stored_data);
},
error: function(error) {
//We'll 404 in the demo, but that's okay. We don't have a 'postIt' service on the
//docs server.
//stored_data = error;
}
}
//Call the asynchronous xhrPost
var deferred = dojo.xhrPost(xhrArgs);
console.log(stored_data);
return stored_data;
}
var xhrArgs = {
url: "query.php",
sync: true, // THIS IS FORCE THE SYNCRONIZATION BETWEEN THE CALLBACK AND THE CODE
postData: query_string,
handleAs: "text",
load: function(data) {
raw_data = dojo.fromJson(data);
stored_data = new dojo.data.ItemFileReadStore({data: raw_data});
console.log(stored_data);
},
error: function(error) {
//We'll 404 in the demo, but that's okay. We don't have a 'postIt' service on the
//docs server.
//stored_data = error;
}
}
除非绝对必要,否则绝对不要使用sync:true
。它挫败了XHR的许多目的,并从AJAX中获得了第一个好处。理想情况下,依赖XHR结果的任何代码都应该在加载
回调中,或者使用然后
(或者Dojo<1.5中的添加回调
)添加到以后的回调中。