JQuery ajax请求 - 全局变量

问题描述 投票:0回答:1

所以,我有这个代码:

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

它将邮政编码发布到服务器,服务器返回与zip对应的城市名称。现在的问题是,我想在done函数之外访问response [0] .city。问题是,我无法宣布它是全球性的。我试图失去var,我读到它声明它是全局的,但是nop。还尝试将其声明为我脚本中的第一件事,在任何函数之外,仍然是nop。它无法访问。我还试图将一个完全不同的变量定义为全局,将响应变量传递给它以保存它。仍然没有。

javascript jquery ajax
1个回答
1
投票

我会使用$.ajax而不是$.post所以我可以使它与async: false同步,然后在$.ajax之前创建变量,如下所示:

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
© www.soinside.com 2019 - 2024. All rights reserved.