【问题标题】:Sending ajax request and receiving response (synchronised)发送ajax请求和接收响应(同步)
【发布时间】:2016-11-21 18:45:14
【问题描述】:

我正在发送 ajax 请求并在我的 js/html 应用程序中处理响应。该设备是 Windows Mobile CE,没有 jquery 支持,设备浏览器 (IE) 不支持事件处理程序,所以我不能使用异步调用。无论如何,我的问题是,在发送事件之前,我想显示一个请稍候消息,并且在收到响应后我想再次隐藏它。

function sendRequest() {
// make please wait visible
document.getElementById("pleasewait").style.display = "block";
console.log("pleasewait visible.");

var XHR = new XMLHttpRequest();
// synch call

XHR.send(sendData);

// suppose it takes 20-30 seconds
console.log("response received :" + XHR.responseText);

XHR.open('POST', 'url', false); 

// make please wait hidden
document.getElementById("pleasewait").style.display = "none";
}

但是,当我运行它时,当我们收到响应(而不是在发送之前)时,pleasewait 元素是可见的,并且即使该过程需要 20-30 秒,也会立即隐藏。控制台消息以正确的顺序显示,但请稍候元素未正确更新。我尝试了一些 setTimeouts 但没有想要的结果。我无法添加一些 jsfiddle,因为很难在遥控器上实现 ajax 请求处理程序。

【问题讨论】:

    标签: javascript html ajax xmlhttprequest response


    【解决方案1】:

    在执行 同步 ajax 请求时,浏览器会冻结,因此 synchronous 请求会阻止显示回流!

    我建议的唯一解决方案是将setTimeout0 持续时间一起使用!

    function sendRequest() {
      document.getElementById("pleasewait").style.display = "block";
      setTimeout(function() {
        var XHR = new XMLHttpRequest();
        XHR.send(sendData);
        console.log("response received :" + XHR.responseText);
        XHR.open('POST', 'url', false);
        document.getElementById("pleasewait").style.display = "none";
      }, 0);
    }

    注意:Here是一些相关信息!

    【讨论】:

    • 成功了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 2011-05-05
    相关资源
    最近更新 更多