Saving data from the d3.js ajaxrequest in a variab

2020-05-06 20:24发布

问题:

I read a lot of posts here about how to save my data in a variable. To do so I created the global variable "arraydates". It needs to be in an array to be used for the axis tick values which is working fine. But only the first console.log within the ajax-request is working. The second one doesn´t give anything. Any clues why? Is it because the Ajaxrequest is asynchronous? And what would be a better solution then? Thanks for suggestions.

var arraydates;

        d3.json("/weather/date.json", function(error, datad) {

        var array = [];
        for(var i in datad)
            array.push( datad[i].date);
            arraydates=array;            

        console.log(arraydates);

        });

console.log(arraydates);

回答1:

Yes — it's the asynchronous nature of ajax requests that affecting what's being console logged. Code that lives outside (and after) the d3.json handler function will execute immediately after the ajax request is initiated but before the response comes back. The link Lars posted above covers all that, but the implication is that you need a global variable, or that any code you want to run after the data is ready has to live inside the d3.json handler function. If you're looking for a cleaner pattern that's slightly less spaghetti -ish and doesn't depend on a global variable, you can set it up like so:

d3.json("/weather/date.json", function(error, datad) {

    var array = [];
    for(var i in datad) {
        array.push( datad[i].date);
    }

    // Call a rendering function, passing in the results
    // of the ajax call (plus the processing). No need for
    // global variables.
    renderMyVisualization(array);
});

function renderMyVisualization(arrayDates) {
    // When this code runs, we have the data and you're
    // ready to render
    d3.selectAll("div").data(arrayDates)
    ...
}


回答2:

Both suggestions are usefull for my situation, but also I have to add that I have several ajax-requests in my code and kind of wanted to clean it up rather than nesting several requests, but now it´s working fine. Thanks!



标签: d3.js