使用JQuery循环Ajax之前的警报 [英] Alert before Ajax request in a loop with JQuery

查看:140
本文介绍了使用JQuery循环Ajax之前的警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一个循环,在执行同步ajax请求之前要求用户进行确认,但它不按顺序工作。这是我的代码:

I am trying to have a loop that asks the user for a confirmation before doing a synchronous ajax request and it is not working in order. This is my code:

<script>
    $(document ).ready(function() {
        for(var i = 0; i < 3; i++) {
            alert("iteration "+i);
            $(".demo").easyOverlay("start");
            $.ajax({
                async: false,
                url: "http://rest-service.guides.spring.io/greeting"
            }).then(function(data) {
               $('.demo').append(data.id);
               $('.demo').append(data.content);            
               $(".demo").easyOverlay("stop");
            });                         
        }       
    });
</script>

我对代码的行为是这样的:

The behaviour I am having with my code is like this:


  • 要求第一次确认。

  • 要求第二次确认。

  • 要求第三次确认。

  • 一个接一个地执行三个ajax调用。

  • Ask for the first confirmation.
  • Ask for the second confirmation.
  • Ask for the third confirmation.
  • Executed the three ajax calls one after the other.

看起来像出于某种原因,所有ajax调用都会被延迟,直到警报全部被确认并且我不知道为什么。我试图在不使用循环的情况下实现同样的目标,并且重复代码3次,我得到了相同的奇怪行为。

It looks like for some reason all the ajax calls gets delayed until the alerts are all confirmed and I don't know why. I tried to achieve my same goal without using a loop and by repeating the code 3 times and I get the same exact strange behaviour.

编辑:

如果我在'then()'中放入以下行来检查html是否实际被修改,我可以在控制台中看到事情按顺序实际发生它们只是在我确认每个警报之前不会出现在浏览器中,这就是给出了执行顺序不正确的印象。因此,我需要弄清楚为什么反映对html所做的更改会延迟并且不会立即完成。

If i put the following line in 'then()' to check if the html is actually modified I can see in the console that the things actually happens in order and they just don't appears in the browser until I confirm every alert and that's what gives the impression that the order of execution is not correct. So I need to figure out why reflecting the changes done to the html is delayed and is not done immediately.

console.log($('.demo').html());


推荐答案

IMO jQuery.Deferred( )对象将是最有前途的方式。

IMO jQuery.Deferred() object will be the most promising way.


  • Deferred对象是 chainable utility 通过调用jQuery.Deferred()方法创建的对象。它可以将多个回调注册到回调队列,调用回调队列,并中继任何同步或异步函数的成功或失败状态。

  • The Deferred object, is a chainable utility object created by calling the jQuery.Deferred() method. It can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.

延迟对象可用于处理异步事件 - 启动操作然后注册将在操作完成时调用的回调。这包括AJAX,虽然还有很多其他用途。

deferred objects can be used for processing asynchronous events - you initiate an action and then register a callback which will be invoked when the action has completed. This includes AJAX, although there are plenty of other uses too.

哪里要求解决

function callAjaxMethod(url, step) {
  return $.Deferred(function() {
        //Confirm box for use inputs
        if(confirm(step))
        {
          //Ajax call 
          $.ajax(url).done(function(data){
             //Do something
             //Update your HTML if needed 
          });
        }
        setTimeout(function() {
          //This will resolve your call again
          this.resolve();
        }.bind(this), 1000);
  })
}

延期对象

var defer = $.Deferred().resolve();
var counters = [1, 2, 3, 4, 5];
$.each(counters, function(key, value) {
    defer = defer.then(function() {
      return callAjaxMethod('URL', value);
    });
});

完成所有操作后会调用

defer.then(function() {
  //It will call when all done
});

少量文档

官方jQuery.Deferred

通过jQuery延迟调用ajax

关于多个jQuery承诺的文章

希望这可以帮助你:)

var $demo = $('#demo');
var ajaxURL = 'https://jsonplaceholder.typicode.com/posts';
function callAjaxMethod(url, step) {
  return $.Deferred(function() {
        //Confirm box for user inputs
        if(confirm(step))
        {
          //Ajax call 
          $.ajax(url).done(function(data){
            //Do something
            //console.log(data);
            
            //Update the HTML OK
            $demo.append(step + ": Success" + "<br/>");
          });
        }
        else
        {
          //Update the HTML when cancel
          $demo.append("<font color='red'>"+ step +": Cancelled </font>" + "<br/>");
        } 
        //Use timeout to get the resolved
        setTimeout(function() {
          this.resolve();
        }.bind(this), 1000);

  })
}
//Defer object
var defer = $.Deferred().resolve();
var counters = ['call 1', 'call 2', 'call 3', 'call 4', 'call 5'];
//Loop your calls
$.each(counters, function(key, value) {
    defer = defer.then(function() {
      return callAjaxMethod(ajaxURL, value);
    });
});

defer.then(function() {
  //It will call when all done
  $(demo).append("<br/><br/>"+"ALL DONE");
});

div
{
  color: blue;
  font-size: 14px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="demo"></div>

这篇关于使用JQuery循环Ajax之前的警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆