Alert before Ajax request in a loop with JQuery

后端 未结 3 1993
囚心锁ツ
囚心锁ツ 2020-12-20 01:25

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:

<         


        
3条回答
  •  情歌与酒
    2020-12-20 01:59

    That is because you should do the looping inside the Ajax request callback. 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.

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

提交回复
热议问题