如何使用 d3.js 同步加载 JSON 数据? [英] How do I load JSON data synchronously with d3.js?

查看:42
本文介绍了如何使用 d3.js 同步加载 JSON 数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的站点首次初始化时,它会查询服务器以取回一些数据.在此数据恢复之前,我无法在页面上布置任何内容.使用d3.js,我可以使用d3.json() 来获取我的数据,但是因为它是异步的,我需要将整个页面逻辑放在回调函数中.如何请求数据并等待数据返回?

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?

推荐答案

不建议在 JavaScript 中使用同步请求,因为它会阻塞整个线程并且在此期间什么也不会完成.用户也不能很好地与网页交互.

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.

如果真的是你想要的,你可以这样做(使用jQuery):

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

但是,即使是 jQuery,也不推荐这样做,正如这里的解释 jQuery.ajax() 文档:

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

Ajax 中的第一个字母代表异步",意思是操作并行发生,完成的顺序没有保证.$.ajax() 的 async 选项默认为 true,表示发出请求后可以继续执行代码.强烈建议不要将此选项设置为 false(从而使调用不再是异步的),因为它会导致浏览器无响应.

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.

最后一点,我看不出是什么阻止了您以异步方式使用 success 属性中的任何函数.大多数时候改变你的设计以使用异步请求是值得的.根据经验,调试使用同步请求的页面是一件痛苦的事情(尤其是当请求没有得到答复时......).

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...).

这篇关于如何使用 d3.js 同步加载 JSON 数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆