Do while javascript issue

后端 未结 3 1403
没有蜡笔的小新
没有蜡笔的小新 2021-01-16 06:46

I\'m trying to send multiple post within a do while loop but the result is not added



        
3条回答
  •  心在旅途
    2021-01-16 07:39

    Due to the async nature of AJAX, by the time your success function runs for any of the resulting AJAX requests, the loop has completed and initval is set to 5. You need to capture the state of initval at the start of each request and use that captured state in the success() method. Closing over the value is the simplest way to do it:

    function action() {
        var initval = 1;
        var endval = 5;
        do {
            var action_string = 'txtuser=someone';
    
            ( function( captured_initval ){
                $.ajax({
                    type: "POST",
                    url: "http://localhost/js.php",
                    data: action_string,
                    success: function(result){
                        $('div#append_result').append(captured_initval + ',
    '); } }); }( initval ) ); initval++; } while (initval <= endval); }

    Understand, though, that one or more requests could get hung up at the server allowing a latter request to complete first, which could result in 1, 2, 5, 3, 4 or something like that.

    Also, using an element's ID is much faster than prefixing the hash selector with the elements tag name. Plus you should avoid re-querying the DOM for your result DIV every time the success runs. Grab it once and use it when needed:

    function action() {
        var initval = 1;
        var endval = 5;
        do {
            var action_string = 'txtuser=someone',
                $AppendResult = $('#append_result');
    
            ( function( captured_initval ){
                $.ajax({
                    type: "POST",
                    url: "http://localhost/js.php",
                    data: action_string,
                    success: function(result){
                        $AppendResult.append(captured_initval + ',
    '); } }); }( initval ) ); initval++; } while (initval <= endval); }

提交回复
热议问题