How do I load JSON data synchronously with d3.js?

若如初见. 提交于 2019-11-27 02:49:31

问题


When my site first initializes, it queries a server to get back some data. I can't lay anything out on the page until this data gets back. With d3.js, I can use d3.json() to get my data, but because it's asynchronous, I need to put the entire page logic in the callback function. How do I request the data and wait for it to come back?


回答1:


You're basically doing it the only way. The callback function has to be the one initiating the rest of your code. You don't need all your code in the callback function though, you can introduce indirection. So the callback function will call another function inside which would be what is currently in your callback function.




回答2:


Using synchronous requests in JavaScript is not recommended as it blocks the whole thread and nothing gets done in the meantime. The user can also not interact well with the webpage.

If it is really what you want, you can do the following (using jQuery):

var jsonData;
jQuery.ajax({
  dataType: "json",
  url: "jsondatafile.json",
  async: false
  success: function(data){jsonData = data}
});

However it is not recommended, even by jQuery, as explained here the jQuery.ajax() documentation:

The first letter in Ajax stands for "asynchronous," meaning that the operation occurs in parallel and the order of completion is not guaranteed. The async option to $.ajax() defaults to true, indicating that code execution can continue after the request is made. Setting this option to false (and thus making the call no longer asynchronous) is strongly discouraged, as it can cause the browser to become unresponsive.

As a final note, I don't see what prevents you from using whatever function there is in the success attribute in an asynchronous way. Most of the times changing your design to use async requests will be worth it. By experience, debugging a page that uses synchronous requests is a pain (especially when the requests don't get answered...).



来源:https://stackoverflow.com/questions/15261313/how-do-i-load-json-data-synchronously-with-d3-js

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