AJAX not updating variable

前端 未结 5 1066
生来不讨喜
生来不讨喜 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:21

    The (first) A in "AJAX" stands for asynchronous. The transaction does not happen immediately, and so your alert() happens quite some time before the remote call completes.

    0 讨论(0)
  • 2020-12-07 03:27

    Your alert is executing before the Ajax request is finished. Try the following. var foo = "";

    $.ajax({
        url: "/",
        dataType: "text",
        success: function(response) {
            foo = "New value:" + response;
    
            alert(foo);
        },
        error: function() {
            alert('There was a problem with the request.');
        }
    });
    
    0 讨论(0)
  • 2020-12-07 03:30

    The problem is that your alert is being fired before the request has been completed. Try this code:

    I've put the alert into the callback function of the $.ajax, which means that the callback function will only be fired after the .ajax part has been completed. This will transfer the new data over, set the variable, THEN alert it, rather than calling the request and alerting the variable at the same time.

    $.ajax({
        url: "/",
        dataType: "text",
        success: function(response) {
            foo = "New value:" + response;
            alert(foo);
        },
        error: function() {
            alert('There was a problem with the request.');
        }
    });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 03:41

    The issue is simple...

    alert(foo);
    

    will execute while the request is being processed and foo will not be altered yet.

    if you do :

    $.ajax({
        url: "/",
        dataType: "text",
        success: function(response) {
            foo = "New value:" + response;
            alert(foo);
        },
        error: function() {
            alert('There was a problem with the request.');
        }
    });
    

    You'll see that it's working as intended

    0 讨论(0)
提交回复
热议问题