简体   繁体   中英

JQuery ajax request - global variable

So, I have this code:

$.post("contacts.php", 
    {zip: $("#zip").val()}, "json").done(function(data){
        var response = JSON.parse(data);
        $("#city").val(response[0].city);
        });}

It posts the zip code to the server, and the server returns the city name corresponding to the zip. Now the problem is, I want to access response[0].city outside of the done function. The problem is, I can't declare it as global. I tried to lose the var, I read that it declares it as global, but nop. Also tried to declare it as the first thing in my script, outside of any functions, still nop. It can't be accessed. I also tried to define a completly different variable as global, pass it the response variable to save it. Still nop.

I would use $.ajax instead of $.post so I can make it synchronous with async: false , then just create the variable before the $.ajax like this:

var city;

$.ajax({
    type: "POST",
    url: "contacts.php",
    data: { zip: $("#zip").val() },
    success: function(data) {
        var response = JSON.parse(data);
        city = response[0].city;
    },
    // by setting async: false the code after the 
    // $.ajax will not execute until it has completed
    async: false
});

// some operation with the city variable

NOTE: as of recently the usage of async: false is deprecated with jQuery and modern browsers. You should find a solution that does not involve using async: false .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM