简体   繁体   English

在异步ajax请求之前运行一个函数

[英]Running a function before async ajax request

I'm trying to run a function before async ajax request. 我正在尝试在异步ajax请求之前运行一个函数。 However function is running after async request gets the respond. 但是,在异步请求获得响应后,函数正在运行。

Is there any way to solve this issue? 有什么方法可以解决这个问题吗?

block();

ajaxRequest= $.ajax({
    url: siteURL+'includes/ajax/action.php',
    type: "POST",
    async: false,
    data: {productID : productID},
    dataType: "json"
});
ajaxRequest.done(function(data) {
            block(true);
            if (data === false) {
                alerts('error title','error info here', 'error', 200);
                return false;
            }
});
ajaxRequest.fail(function(jqXHR, textStatus) {block(true); alerts('error title','error info','error');});
confirm();

I run more functions after these codes. 我在这些代码后运行了更多的函数。 However as I stated before, block(); 但正如我之前所说, block(); function is waiting till async ajax request is getting response. 函数正在等待异步ajax请求得到响应。

If I don't run asynchronous, then I get block() and confirm() functions running at the same time so return false; 如果我不运行异步,那么我会同时运行block()confirm()函数,所以return false; losing all the meaning. 失去了所有的意义。

PS I run these codes when a form is submitted so if async request is failed I don't want it to run any other code after it. PS我在提交表单时运行这些代码,因此如果异步请求失败,我不希望它在其后运行任何其他代码。 However when it is asynchronously running block() is waiting till response is returned. 但是当它异步运行时, block()等待直到返回响应。

Your problem is async:false . 你的问题是async:false Your request is NOT an async request, it is a sync request. 您的请求不是异步请求,而是同步请求。 It blocks javascript code and browser rendering from happening while the request is being processed. 它会阻止javascript代码和浏览器呈现在处理请求时发生。 With your current setup, there should be no harm in removing async: false, thus making it async. 使用当前的设置,删除async: false,应该没有任何害处async: false,从而使其异步。

block();

ajaxRequest= $.ajax({
    url: siteURL+'includes/ajax/action.php',
    type: "POST",
    data: {productID : productID},
    dataType: "json"
});
ajaxRequest.done(function(data) {
            block(true);
            if (data === false) {
                alerts('error title','error info here', 'error', 200);
                return false;
            }
});
ajaxRequest.fail(function(jqXHR, textStatus) {block(true); alerts('error title','error info','error');});
ajaxRequest.always(confirm);

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

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