jQuery ajax loop and iteration scope

前端 未结 4 690
终归单人心
终归单人心 2021-01-25 23:07

I\'m wondering why in the code below the i variable still shows \"5\" instead of showing \"1\" then \"2\" the

相关标签:
4条回答
  • 2021-01-25 23:31

    you can fix this using closures, wrapping the value of i:

    for (var i = 0; i < 5; i++) {   
       (function(val){
          $.ajax({
              url: '/echo/html/',
              method:'post',
               data: {
                   html: 'Ajax data'
               },
               success: function (resp) {
                   $('#success').append(val);
               }
           })
           $('#outsideAjax').append(val); // is okay
         })(i);
    }
    
    0 讨论(0)
  • 2021-01-25 23:32

    Solution using Function#bind():
    http://jsfiddle.net/RQncd/1/

    for (var i = 0; i < 5; i++) {   
      $.ajax({
        url: '/echo/html/',
        method:'post',
        data: {
          html: 'Ajax data'
        },
        success: (function (i, resp) {
          $('#success').append(i);
        }).bind(null, i)
      });
      $('#outsideAjax').append(i);
    }
    
    0 讨论(0)
  • 2021-01-25 23:48

    This is due to Closures in JavaScript. Here's the fix -

    for (var i = 0; i < 5; i++) { 
       (function(i){
        $.ajax({
            url: '/echo/html/',
            method:'post',
            data: {
                html: 'Ajax data'
            },
            success: function (resp) {
                $('#success').append(i) 
            }
        })
        })(i);
    
        $('#outsideAjax').append(i); 
    }
    
    0 讨论(0)
  • 2021-01-25 23:53

    fiddle Demo

    var i = 0;
    
    function ajax_call() {
        $.ajax({
            url: '/echo/html/',
            method: 'post',
            data: {
                html: 'Ajax data'
            },
            success: function (resp) {
                $('#success').append(i++);
                if (i < 5) {
                    ajax_call();
                }
            }
        });
        $('#outsideAjax').append(i);
    };
    ajax_call();
    
    0 讨论(0)
提交回复
热议问题