D3 Bar Graph example not working locally

前端 未结 3 1049
灰色年华
灰色年华 2020-11-27 21:09

I am very new to D3, and wanted to see how an example would work locally. I copied and pasted the bar graph code to a local file called index.html, and also copied over the

3条回答
  •  情深已故
    2020-11-27 21:54

    As already stated, you're most likely encountering a CORS issue with the XHR in the d3 library for an external resource to parse the JSON data.

    However, here is another solution: use JSONP and Express/Node.js in conjunction with a jQuery function to initiate a client-side request for JSON, instead of using the original wrapper for d3 functions.

    Had to remove the original d3.json wrapper and populate the adjacency diagrams with data from the request. Begin by cloning or downloading jsonp-d3-experiment and start the server using node server.js. Of course you need to have Node.js installed globally, beginning with Node Packaged Modules (npm). Copy your program into a subdirectory.

    Put your JSON data in the jsonp-d3-experiment directory and modify server.js to route the request to your data:

    // Return data from callback
    server.get('/example', function(req, res)
    {
      // Read the JSON data and send to JSONP response
      readJSON('example.json', function (e, json)
      {
        if (e) { throw e; }
        res.jsonp(json);
      });
    });
    

    Below is the code I modified for a co-occurrence matrix. I moved the entire script into $.getJSON and removed the d3.json function altogether.

    
    

    Notice that now the JSON data is in result, so the easiest thing to do was to assign it to miserables.

    Note: jQuery is required for this solution.

    Now you should be able to locally open and render all your d3 visualizations without hosting them on a server--simply open them in your browser straight from your local filesystem.

    HTH!

提交回复
热议问题