AJAX not updating variable

前端 未结 5 1074
生来不讨喜
生来不讨喜 2020-12-07 02:51

jQuery

I am making an AJAX request that updates the value of a variable (foo) with a response from the server. Here is the code I am using:



        
5条回答
  •  抹茶落季
    2020-12-07 03:32

    At the point when you alert the value of foo, the success handler has not yet fired. Since it is the success handler that reassigns the variable, its value remains an empty string.

    The timeline of events looks something like this:

    1. foo is assigned the empty string
    2. AJAX request created and dispatched.
    3. The value of foo is alerted. (Note that foo hasn't changed yet)
    4. AJAX request completes.
    5. foo = "New value:" + this.responseText;

    Since we want to alert the value of foo after it has changed, the solution is to put the alert in the success callback.

    Now it will be executed after the AJAX response is received.

提交回复
热议问题