Saving data from the d3.js ajaxrequest in a variable to create axis with data

后端 未结 2 924
眼角桃花
眼角桃花 2021-01-26 02:39

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 tic

相关标签:
2条回答
  • 2021-01-26 03:07

    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!

    0 讨论(0)
  • 2021-01-26 03:29

    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)
        ...
    }
    
    0 讨论(0)
提交回复
热议问题