AJAX not updating variable

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

提交回复
热议问题