AJAX not updating variable

前端 未结 5 1078
生来不讨喜
生来不讨喜 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: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.');
        }
    });
    

提交回复
热议问题