DOJO xhrGet how to use returned json object?
How can I access the data returned from the xhrGet outside of the get itself? Firebug shows that the "json" object has an array called results, which stores the json Object from the response, but when I try to access it i开发者_JS百科t is null. So: how do I access the received data on the last code line?
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);
By default dojo.xhrGet is called asynchronously, so console.log(json.results) is null because it's run just after dojo.xhrGet, but before response comes from server.
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'));
The result is:
1 false
2 response - ['some data from server']
3 xhrGet.results[0] - same data as in 'response' accessed via xhrGet
The simplest way to access your retrieved JSON data is to assign it to a document-level variable within the xhrGet load function:
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);
}
});
Yeah, no. I've since learned a much better way, and forgot to come back and fix this answer, so it deserves the downvotes it's accrued.
The proper way to deal with data fetched from dojo.xhrGet, jQuery.ajax, or any other asynchronous data fetch is to write a function to process its results, and pass it to xhrGet as the load argument, like so:
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);
}
精彩评论