简体   繁体   English

在 JQuery 循环中的 Ajax 请求之前发出警报

[英]Alert before Ajax request in a loop with JQuery

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.我试图有一个循环,在执行同步 ajax 请求之前要求用户进行确认,但它无法正常工作。 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:我的代码的行为是这样的:

  • 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调用。

It looks like for some reason all the ajax calls gets delayed until the alerts are all confirmed and I don't know why.看起来由于某种原因,所有 ajax 调用都被延迟,直到警报全部确认,我不知道为什么。 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.我试图在不使用循环的情况下通过重复代码 3 次来实现我的相同目标,但我得到了完全相同的奇怪行为。

Edit:编辑:

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.如果我将以下行放在“then()”中以检查 html 是否实际被修改,我可以在控制台中看到这些事情实际上是按顺序发生的,并且在我确认每个警报之前它们不会出现在浏览器中,那就是是什么给人的印象是执行顺序不正确。 So I need to figure out why reflecting the changes done to the html is delayed and is not done immediately.所以我需要弄清楚为什么反映对 html 所做的更改会延迟而不是立即完成。

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

IMO jQuery.Deferred() object will be the most promising way. IMO jQuery.Deferred()对象将是最有前途的方式。

  • The Deferred object, is a chainable utility object created by calling the jQuery.Deferred() method. Deferred 对象是通过调用 jQuery.Deferred() 方法创建的chainable utility对象。 It can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.它可以将多个回调注册到回调队列中,调用回调队列,并中继任何同步或异步函数的成功或失败状态。

  • 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. deferred objects可用于处理异步事件 - 您启动一个动作,然后注册一个回调,该回调将在该动作完成时调用。 This includes AJAX, although there are plenty of other uses too.这包括 AJAX,尽管还有很多其他用途。

Where asks for resolved哪里要求解决

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);
  })
}

Deferred object递延对象

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

It will call when all done全部完成后它会调用

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

Few of the documentation文档很少

Official jQuery.Deferred官方 jQuery.Deferred

Call ajax via jQuery deferred's 通过 jQuery 延迟调用 ajax

Article on Multiple jQuery promises 关于多个 jQuery 承诺的文章

Hope this helps you :)希望这对你有帮助:)

 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>

That is because you should do the looping inside the Ajax request callback.那是因为您应该在 Ajax 请求回调中进行循环。 When you do it this way, the whole code is executed in a synchronic manner, whilst if you were to do so when the Ajax request callback is invoked, the requests and alerts would be executed like you would expect.当您这样做时,整个代码以同步方式执行,而如果您在调用 Ajax 请求回调时这样做,则请求和警报将按您预期的方式执行。

Edit: Here is an example: (generic, you can customize it to your needs)编辑:这是一个示例:(通用,您可以根据需要对其进行自定义)

do(3)

function do(i) {
     if (i === 0) return
     $.ajax({...}).then(function() {
        alert(...)
        do(i-1) 
     })
 }

Everytime ajax call fire it first ask for confirmation.每次 ajax 调用 fire 它首先要求确认。 If you allow then only ajax call fire and call for next ajax call and ask for confirmation and so on.. Please check below snippet for more understanding.如果您允许,则仅 ajax 调用 fire 并调用下一个 ajax 调用并要求确认等等。请查看以下代码段以获取更多理解。

//call first time
doAjax(1,3)
//Function to call ajax repeatedly
function doAjax(arrCount,maxCount) 
{
    if (confirm("iteration "+arrCount)) {
        $.ajax({
            url: 'myUrl',
            type: "POST",
            data: {
                // data stuff here
            },
            success: function (data) { 
                arrCount++;
                //Next ajax call when current ajax call has been finished.
                if(arrCount<=maxCount){
                    doAjax(arrCount,maxCount);
                }               
            }         
        });
    }
}

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

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