DOJO xhrGet How to use the returned json object?

How can I access data returned from xhrGet outside of get itself? Firebug shows that the "json" object has an array called the result, which stores the json Object from the response, but when I try to access it, it is zero. So: how do I access the data on the last line of code?

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); 
+4
source share
2 answers

By default, dojo.xhrGet is called asynchronously, so console.log (json.results) is null because it starts immediately after dojo.xhrGet, but before the response comes from the 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')); 

Result:

1 false

2 answer - ['some data from the server']

3 xhrGet.results [0] - the same data as in 'response', access via xhrGet

+3
source

The easiest way to access the received JSON data is to assign it to a document level variable in 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); } }); 

Well no. Since then I have learned much better, and forgot to return and correct this answer, so it deserves to be credited.

The correct way to process data obtained 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 load , for example:

 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); } 
-1
source

All Articles