【问题标题】:Pass returned array from (Ajax output) to use as GLOBAL VARIABLES everywhere从(Ajax 输出)传递返回的数组以在任何地方用作全局变量
【发布时间】:2015-07-18 18:14:35
【问题描述】:

我正在尝试从 Ajax 输出返回数组中的两个变量,以便在其他地方的另一个单独函数中使用:

但不知道如何将其传递到新功能?

我在这里的尝试:

var ip,country;

function getVisitorData(callback) {
    $.ajax({
        type: "GET",
        url: "http://freegeoip.net/json/",
        dataType: "json",
        async: true,
        success: function (response) {
            ip = response.ip;
            country = response.country_code;
            callback(response);
        },
        error: function (response) {
            alert("IP thing didn't work.");
        }
    });
}

function callback(response) {
    return [ip, country];
    //alert(ip + country); /* <- it works here */
}

getVisitorData(callback);

jQuery(document).ready(function () {
    var data = getVisitorData(callback);
    var ip = data[0];
    var country = data[1];
    alert(ip + country);
});

更新:

我想使用输出 作为 GLOBAL VARIABLES

所以,就这样获取/使用它:

jQuery(document).ready(function () {
    alert(ip)
});

抱歉,如果我对此不够清楚!

非常感谢!

【问题讨论】:

  • 关于您的更新,您在这里大错特错,抱歉!异步 JavaScript 根本不能那样工作。听听那些告诉你你需要调用一个带有返回数据的函数而不是仅仅将它存储在一个全局变量中的人,并听取他们的建议。只有这样,你才能成功解决问题。您可以使用回调,也可以使用承诺——这只是做同一件事的两种方式。你不能做的只是将数据存储在一个全局变量中,并期望它在你发出 ajax 请求后可用。
  • 我更新了您的一个小提琴以将其变成一个工作示例:jsfiddle.net/mea2nr7t/1
  • 你不能做的是“返回”数据或将其留在全局变量等中。这就是问题所在:需要数据的代码如何知道何时实际从服务器接收到数据?知道数据准备就绪的唯一方法是调用回调。

标签: javascript jquery ajax callback jquery-callback


【解决方案1】:

我倾向于在这里做出承诺:

var ip = {};
var country = {};
var getstuff = {};

function callback(response) {
    ip = response.ip;
    country = response.country_code;
  // not really needed  return [ip, country];
}

function getVisitorData() {
    getstuff = $.ajax({
        type: "GET",
        url: "http://freegeoip.net/json/",
        dataType: "json",
        async: true
    }).done(callback)
    .fail(function (response) {
        alert("IP thing didn't work.");
    });
}
jQuery(document).ready(function () {
    getVisitorData();
    getstuff.done(function () {
        alert(ip + country);
    });
});

它正在运行:http://jsfiddle.net/MarkSchultheiss/7bmnsvay/

【讨论】:

  • 谢谢@Mark Schultheiss!如果我的问题不清楚,对不起!我已经更新了它。只想将输出用作 GLOBAL VARIABLES !
  • 那应该可以var ip = {}; var country = {};
  • 注意:jQuery(document).ready(function () { var data = getVisitorData(callback); var ip = data[0]; var country = data[1]; alert(ip + country); }); 你定义了新变量
【解决方案2】:
function getVisitorData(callback) {
    $.ajax({
        type: "GET",
        url: "http://freegeoip.net/json/",
        dataType: "json",
        async: true,
        success: function (response) {
            ip = response.ip;
            country = response.country_code;
            callback(response);
        },
        error: function (response) {
            alert("IP thing didn't work.");
        }
    });
}
function callback(data) {
    var ip = data[0];
    var country = data[1];
    return [ip, country];
}

jQuery(document).ready(function () {
    getVisitorData(callback);
});

callback 函数中进行数据操作,而不是在任何其他函数中。欲了解更多信息,请访问Callback function

【讨论】:

  • 感谢@vinayakj,但我仍然不知道如何使用之后的输出。我想单独使用ipcountry 作为全局变量,就像这样:jQuery(document).ready(function(){ alert(ip) });
  • 所以如果我对此不够清楚,我已经更新了问题!
【解决方案3】:

创建一个全局对象。

变量 objMyData={};

在该对象中存储 ip 和国家代码。

objMyData.IP=响应.IP; objMyData.Country= response.country_code;

现在将 objMyData 对象作为参数传递给任何函数。

【讨论】:

  • 谢谢@Saravana!这] 是我的尝试 (jsfiddle.net/uL5jnukd),请您检查一下并告诉我错误是什么?请原谅我是新手!谢谢!
  • 这是我们很多人不知道的常见问题是,在你的服务调用成功或失败之前,你的服务调用旁边的行会执行,所以你需要设置一些超时 //创建一个全局对象。 var objMyData = {}; jQuery(document).ready(function () { //现在将 objMyData 对象作为参数传递给任何函数。getVisitorData(objMyData); setTimeout(function(){ console.log(objMyData); }, 500); });
【解决方案4】:

我不知道为什么你需要在你的回调中返回一个数组。由于 ajax 是异步的,它不会等到响应到来,它会执行其余的语句。所以返回值会给你未定义的。只有在响应到来后,您才能使用/分配响应。

function getVisitorData(callback) {
    return $.ajax({
        type: "GET",
        url: "http://freegeoip.net/json/",
        dataType: "json",
        async: true

    });
}

jQuery(document).ready(function () {

    $.when(getVisitorData())
    .done(function(respone) {
      var ip = response.ip;
      var country = response.country_code;
      //here you can trigger a custom event with the values, wherever you need, just bind the event and use the data.
       $(document).trigger("responseDataPublished", [ip, country]);
    })
    .fail(function(response){
       alert("IP thing didn't work.");
    });
});

【讨论】:

  • 谢谢@jrath!如果我的问题不清楚,对不起!我已经更新了它。只想将输出用作 GLOBAL VARIABLES !
【解决方案5】:

这是我们很多人不知道的常见问题是,在你的服务调用成功或失败之前,你的服务调用旁边的行会执行,所以你需要设置一些超时

//创建一个全局对象。 var objMyData = {}global object;

函数 getVisitorData() {function call $.ajax({`ajax 类型:“获取”, 网址:“http://freegeoip.net/json/”, 数据类型:“json”, 异步:真, 成功:功能(响应){ //将ip和国家代码存储在该对象中。 objMyData.ip = response.ip; objMyData.Country = response.country_code; }, 错误:函数(响应){ alert("IP 事情没用。"); } }); }

jQuery(document).ready(function () { //现在将 objMyData 对象作为参数传递给任何函数。 getVisitorData();method call setTimeout(function(){ console.log(objMyData); }, 500); });

【讨论】:

    猜你喜欢
    • 2019-04-05
    • 2014-01-16
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多