同步Ajax请求"锁定"浏览器浏览器、Ajax、QUOT

2023-09-10 18:27:44 作者:半疯半癫半痴傻

我有几个jQuery的Ajax请求,它必须是同步的,但他们保持锁定/冷冻该浏览器中,直至接收到响应。我的主要问题是,直到接收到响应我要显示一个旋转图标,但由于冻结微调不被显示,即使是奇迹般地不动画。

I have a couple of jQuery Ajax requests, which have to be synchronous, but they keep locking/freezing the browser, until the response is received. My main problem is, that until the response is received I have to display a spinning icon, but due to the freezing the spinner is not displayed and even if it miraculously is it doesn't animate.

这是事件显示微调,并发送请求:

This is the event displaying the spinner and sending the request:

$(document).on('click', '#open-button', function () {

    var input = "some text";
    var wrapper = $('#wrapperWindow');
    wrapper.children().animate({
        opacity: 0
    }, 500);
    wrapper.children().remove();
    wrapper.append('<div id="loading-spinner" style="display:none;"></div>');
    var spinner = $('#loading-spinner');
    spinner.css({
        backgroundImage: 'url("img/loading.gif")',
        opacity: 0
    });
    spinner.show();
    spinner.animate({
        opacity: 1
    }, 500);

    var dataForTab = requestData(input); //<-- the request

    if (dataForTab.length > 0) {
        //do stuff
    }

});

请求:

function requestData(input) {

    var result = null;

    $.ajax({
        async: false,
        type: "POST",
        url: "/some/url?input=" + input,
        dataType: "json",
        retryLimit: 3,

        success: function (json) {
            result = json;
        },

        error: function (xhr, err) {
            console.log(xhr);
            console.log(err);
        }
    });

    return result;
}

直到请求返回所接收到的JSON数据,一切都停止的移动的。我怎样才能解决这个问题吗?

Until the request returns the received JSON data, everything stops moving. How can I fix this please?

推荐答案

这是同步请求的实质,他们锁定。您可能要尝试将请求移动到一个 网络工作者 。这里有一个 示例 (不使用XHR,但它可以给你一个实现想法)

That's the essence of synchronous requests, they are locking. You may want to try to move the requests to a web worker. Here's an example (not using XHR, but it can give you an implementation idea)

一个网络工作者在一个单独的文件中实现,该脚本可以是这样的:

A web worker is implemented in a separate file, the scripting can look like:

onmessage = function (e) {
var result = null;

    $.ajax({
        async: false,
        type: "POST",
        url: "/some/url?input=" + input,
        dataType: "json",
        retryLimit: 3,

        success: function (json) {
            result = json;
            postMessage({result: result});
        },

        error: function (xhr, err) {
            postMessage({error: err});
        }
    });

}