如何在get本身之外访问从xhrGet返回的数据? Firebug显示“json”对象有一个名为results的数组,它存储响应中的json对象,但是当我尝试访问它时它是null。那么:如何访问最后一个代码行上的接收数据?
var json = dojo.xhrGet({
url :'/disease_web/graphMlDownload/getEdgeInformation/', handleAs:"json",content : { edgeid : edgeId, graphname:this._canvas.path},
load:function(response){
return response;
}
});
console.log(json.ioArgs);
console.log(json.results);
答案 0 :(得分:3)
默认情况下,dojo.xhrGet是异步调用的,因此console.log(json.results)为null,因为它在dojo.xhrGet之后运行,但在响应来自服务器之前。
var xhrGet = dojo.xhrGet({
url: "/some_rul",
handleAs: "json",
handle: function(response) {
console.info(2,'response',response);
console.info(3,'xhrGet.results[0]',xhrGet.results[0]);
}
});
console.info(1,xhrGet.hasOwnProperty('results'));
结果是:
1假
2回复 - ['来自服务器的一些数据']
3 xhrGet.results [0] - 与通过xhrGet访问的'响应'中的数据相同
答案 1 :(得分:-1)
访问检索到的JSON数据的最简单方法是将其分配给xhrGet加载函数中的文档级变量:
var fetchedData = null;
function parseResponse() { /* do something meaningful */ }
dojo.xhrGet({
url: "{{dataUrl}}dojo/LICENSE",
handleAs: "json",
preventCache: true,
load: function(response){
// save for later
window.fetchedData = response;
// do whatever processing we want with the returned data
parseResponse();
},
error: function(error){
alert("Couldn't fetch your data: " + error);
}
});
处理从dojo.xhrGet,jQuery.ajax或任何其他异步数据提取获取的数据的正确的方法是编写一个函数来处理其结果,并将其传递给xhrGet作为加载参数,如下所示:
var request = dojo.xhrGet({ url :'/disease_web/graphMlDownload/getEdgeInformation/',
handleAs: "json",
content : {edgeid : edgeId, graphname:this._canvas.path},
load: doSomethingWithMyEdges
});
function doSomethingWithMyEdges(json_results) {
console.log(json_results);
}