douzheren3349 2015-11-11 14:02
浏览 27
已采纳

Javascript不会更新用PHP编写的变量

I have a javascript function that calls an AJAX, like this:

function addSquadronByID(id) {
        $.ajax
        ({
            type: "POST",
            url: "server/get_squadron.php",
            data: {
                'id': id,
                'counter': squadron_counter
            },
            cache: false,
            success: function (data) {
                squadron_counter++;
            },
            error: function () {
                alert("AJAX error.");
            }
        });
    }
}

Outside the document.ready, the variable is initialized like this var squadron_counter = 0;

This function perfectly works while I call it in the page, but if I try to use PHP to write it in the page, like this:

        $list_squadrons = $DB->Execute($query);
        while(!$list_squadrons->EOF){
            $currentSquadron_id = $list_squadrons->fields["squadron_id"];
            $currentSquadron_number = $list_squadrons->fields["squadrons"];
            echo "addSquadronByID($currentSquadron_id);
";
            $list_squadrons->MoveNext();
        }

The function writes into the document.ready() the correct calls, but squadron_counter is always zero, even if the function works. My only idea is that it works this way because javascript calls all the functions at once and does not wait to complete the first one before executing the second one, etc.. but how do I solve this?

HTML output as requested:

addSquadronByID(3, squadron_counter);
addSquadronByID(5, squadron_counter);
addSquadronByID(6, squadron_counter);

This is put into a

$( document ).ready(function() {
});

inside a <script> tag.

  • 写回答

1条回答 默认 最新

  • dongwen4487 2015-11-11 16:38
    关注

    I think your idea about JS calling all functions without waiting for the first one to complete is in the right direction. This is called "asynchronous requests". Please refer to How to return the response from an asynchronous call? for a detailed explanation.

    The idea is to send your 3 requests and then wait for all of them to complete before checking the value of your squadron_counter variable (or whatever data you have updated in your success callbacks).

    Then if my understanding is correct, you do not know how to implement this waiting?

    Since you are using jQuery, the implementation is super simple. Note first that your jQuery.ajax request returns a Deferred object. So simply keep a reference of the Deferred object created by each AJAX request you send. Then you could use for example jQuery.when with a callback in its then method to wait for all your requests to complete:

    function addSquadronByID(id) {
        return jQuery.ajax({ /* ... */ }); // returns a Deferred object.
    }
    
    var d1 = addSquadronByID(3),
        d2 = addSquadronByID(5),
        d3 = addSquadronByID(6);
    
    jQuery.when(d1, d2, d3).then(
        // callback executed on success of all passed Deferred objects.
        function () {
            console.log(squadron_counter);
        }
    );
    

    Demo: http://jsfiddle.net/btjq7wuf/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法