【问题标题】:Delay liquid page render until after Ajax returns data延迟液体页面渲染,直到 Ajax 返回数据之后
【发布时间】:2018-05-22 17:54:45
【问题描述】:

我正在使用 Liquid,并且可以访问服务器端和客户端。我想一次获取用户位置,然后根据用户位置呈现不同的液体元素。所以隐藏div是行不通的。 我实际上需要将渲染延迟半秒,直到通过 Ajax 返回国家代码。然后我可以从那里拿走它。我试过了,但没有运气,它并没有延迟页面渲染,它只是延迟了我的消息记录到控制台。

<script>
   $(window).load(function () {
      setTimeout(function(){ console.log("waiting 2 secs..");
        },2000); // set the time here
    });

  jQuery.ajax( {
    url: '//freegeoip.net/json/',
    type: 'POST',
    dataType: 'jsonp',
    success: function(location) {
      {% assign user_country = location.country_code %}
      console.log("Hey this is the country code " + location.country_code);
    }
  });
</script>

【问题讨论】:

  • 你为什么不用.done()
  • 你不需要 jsonp...当包含 origin 时,它将是 CORS 兼容的
  • type=post 对jsonp 没有影响。 jsonp 只能用一个新的脚本标签来请求,而这个标签只用一个 GET 请求来请求
  • 我想你们都错过了问题的重点。我的代码不起作用。即使使用async: false,页面也会在 ajax 返回之前呈现。我需要暂停页面加载的渲染,直到 ajax 返回之后。

标签: javascript jquery liquid


【解决方案1】:

您不应使用jsonp,因为这不是最佳做法。

正如 Sam 指出的,您可以使用 done()

jQuery.ajax({
    url: '//freegeoip.net/json/',
    type: 'POST',
    async: false,
    success: function(location) {
      {% assign user_country = location.country_code %}
      console.log("Hey this is the country code " + location.country_code);
    }
}).done(function() {
  // CODE HERE WILL ONLY RUN ONCE AJAX REQUEST IS COMPLETED
});

【讨论】:

    猜你喜欢
    • 2021-06-06
    • 2021-08-30
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多