简体   繁体   English

如何强制同步执行getJSON?

[英]How to force synchronous execution of getJSON?

For a school history project, I'm making a timeline webpage ( live here ). 对于一个学校历史项目,我正在制作一个时间轴网页( 在此处直播 )。 To avoid having to repeatedly type the details for each, I put them in a spreadsheet and exported it as JSON . 为了避免重复输入每个细节,我将它们放在电子表格中并导出为JSON

In the nav, I created links labelled with the year of the event using Javascript. 在导航中,我使用Javascript创建了标有活动年份的链接。

I want to then use slick.js, a jQuery plugin, to turn the nav into a carousel, as demonstrated an the /slick-test-static.html of the live website linked above. 然后,我想使用jQuery插件slick.js将导航变成轮播,如上面链接的实时网站的/slick-test-static.html所示。

My code: 我的代码:

$(document).ready(function(){
      $.getJSON("data.js", function(result){
        for (var i = 0; i < result.length; i++){
          var string = JSON.stringify(result[i]);
          var parsed = JSON.parse(string);

          $('.slider').append("<li><a href=\"#" + parsed.number + "\">" + parsed.year + "</a></li>");
        }
      });

      $('.slider').slick({
        slidesToShow: 8,
        slidesToScroll: 5,
        autoplay: true,
        autoplaySpeed: 3000
      });
    });

The links are created, but the slider isn't. 链接已创建,但滑块未创建。 I made a page where the links are created not using JSON, and it worked fine. 我制作了一个页面,其中的链接不是使用JSON创建的,并且工作正常。

I think the problem is because the getJSON method is asynchronous, so the browser tries to create the slider before any items are even added to the slider. 我认为问题是因为getJSON方法是异步的,因此浏览器会尝试在甚至没有任何项添加到滑块之前就创建滑块。 First, is this the problem? 首先,这什么问题? If so, what's the best way to fix it? 如果是这样,修复它的最佳方法是什么?

You can't make this synchronous. 您无法使其同步。 With ES6 you can "fake" waiting on asynchronous actions using async and await but what it's doing is essentially the same as what you need to do to make this work. 使用ES6,您可以使用asyncawait来“伪造”等待异步操作,但是它的工作本质上与完成这项工作所需的工作相同。

You need to stick your $('.slider').slick(... code inside of the $.getJSON callback. You should not initialize the slider until the async callback is made. 您需要将$('.slider').slick(... $.getJSON $('.slider').slick(...代码$.getJSON$.getJSON回调中。 $.getJSON异步回调之前,不要初始化滑块。

Not sure if this helps for your concrete question, but you can indeed make synchronous JSON requests. 不知道这是否对您的具体问题有所帮助,但是您确实可以发出同步JSON请求。

The asynchronous request would be (in vanilla JS): 异步请求将是(在原始JS中):

var request = new XMLHttpRequest();
request.open("GET", "/bar/foo.txt", true); // Note the `true` here.
request.send(null);                       // When set to true, the request
                                         // will be asynchronous.
if (request.status === 200) {
  console.log("ok");
}

While the synchronous request would be: 而同步请求将是:

var request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous
request.send(null);

if (request.status === 200) {
  console.log("ok");
}

You have some documentation here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests 您在此处有一些文档: https : //developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM