【问题标题】:Not update css on chrome when AjaxAjax 时不更新 chrome 上的 css
【发布时间】:2018-06-20 06:08:14
【问题描述】:

我需要显示带有多个 ajax 请求的进度条。它们不应该是异步的,因为每个请求都依赖于前一个请求。一切正常,除了进度条。这在 Chrome 中对我不起作用。在 Firefox 中它可以完美运行。执行了几次测试,我意识到当有多个没有异步的请求时,chrome 肯定不会更新 html 的任何属性。

我有这个测试代码:

$('#run').click(function(){
  color_text();
});

function color_text(){

    console.log("Coloring...");

    sleep();
    console.log('Load 1');
    $('#text').html('Test 1');

    sleep();
    console.log('Load 2');
    $('#text').html('Test 2');

    sleep();
    console.log('Load 3');
    $('#text').html('Test 3');

}



function sleep() {
  $.ajax({
      url: '/echo/html/',
      async: false,
      data: {
          html: "<p>Text echoed back to request</p>",
          delay: 3
      },
      method: 'post',
      update: 'target'
  }).done( function( data ){
        result = data;
         $('#text').html('Test Loaded');
    })
}
<html>
<head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
  <body>
   <button id="run">
     <h2>Run</h2>
   </button>
   <hr>
   
<div id="text"> Test</div>

</body>
</html>

在此链接中,您注意到的不仅仅是更新https://jsfiddle.net/arturoverbel/bgm4pa10/10/

【问题讨论】:

  • 嵌套onprogresss,然后在最里面添加eventObj.loadeds。 developer.mozilla.org/en-US/docs/Web/API/…
  • They should not be asynchronous 他们当然应该这样做,事实上大多数浏览器将来都会阻止它,除非在 webworker 中使用。
  • 我明白了。但奇怪的是,这种方法在 Chrome 中无论如何都不起作用。
  • 好的。在回答这个问题时,我必须异步工作。你是对的,最好使用推荐的@Keith

标签: javascript jquery html css ajax


【解决方案1】:

同步请求不好。它们会阻塞主要的 javascript 线程并使您的应用程序冻结,它们是 deprecated:

注意:从 Gecko 30.0 开始(Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27)、Blink 39.0 和 Edge 13,同步请求 由于对 用户体验。

您应该在您的应用中注意到这一点。请注意,当您在 JSFiddle 中点击“运行”时,整个页面是如何冻结的。

但是,您仍然可以通过 Promise 异步实现您想要的。

promise 的关键特性是你可以返回另一个promise,它会继续这个链。添加一点递归性,您就得到了一个不错的解决方案,不会冻结整个页面。

使用您的示例:

$('#run').click(function() {
    color_text();
});

function color_text() {

    console.log("Coloring...");

    run();

}

function run(count = 0) {

    // make a request. consider using `fetch()` 
    return makeRequest().then(result => {

        // if we're not done, 
        // return `run()` again which runs this
        // whole promise again
        if (result != 'done!') {
            // optionally update your html
            $('#text').html(count);
            return run(count + 1);
        }

        $('#text').html(result);
    });

}

https://jsfiddle.net/je2m0pxa/

【讨论】:

  • 这适用于 Chrome。非常感谢。虽然更好,但我会异步工作。
猜你喜欢
  • 1970-01-01
  • 2020-12-14
  • 2014-06-05
  • 2018-01-29
  • 1970-01-01
  • 2016-04-17
  • 2014-07-05
  • 1970-01-01
  • 2018-01-20
相关资源
最近更新 更多