DOJO xhrGet how to use returned json object?

巧了我就是萌 提交于 2020-01-12 08:49:09

问题


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 it 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);

回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/4044489/dojo-xhrget-how-to-use-returned-json-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!