最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Pass returned array from (Ajax output) to use as GLOBAL VARIABLES everywhere - Stack Overflow

programmeradmin2浏览0评论

I'm trying to return from the Ajax output, two variables in array, to use in another separate functions in another places:

But can't figure out How to pass it out to the new functions?

My attempt here:

var ip,country;

function getVisitorData(callback) {
    $.ajax({
        type: "GET",
        url: "/",
        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);
});

Update:

I want to use the output as GLOBAL VARIABLES !

So, get/use it just like that:

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

Sorry if I wasn't clear enough about that!

Many thanks in advance!

I'm trying to return from the Ajax output, two variables in array, to use in another separate functions in another places:

But can't figure out How to pass it out to the new functions?

My attempt here:

var ip,country;

function getVisitorData(callback) {
    $.ajax({
        type: "GET",
        url: "http://freegeoip/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);
});

Update:

I want to use the output as GLOBAL VARIABLES !

So, get/use it just like that:

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

Sorry if I wasn't clear enough about that!

Many thanks in advance!

Share Improve this question edited Jul 19, 2015 at 5:00 Homer asked Jul 18, 2015 at 18:14 HomerHomer 3551 gold badge5 silver badges18 bronze badges 8
  • 1 possible duplicate of How to return the response from an asynchronous call? – doldt Commented Jul 18, 2015 at 18:23
  • possible duplicate of Can't parse and return ajax string to jquery variable – vinayakj Commented Jul 18, 2015 at 18:29
  • 1 Regarding your update, you're very much on the wrong track here, sorry! Asynchronous JavaScript simply doesn't work that way. Listen to the people who are telling you that you that you need to call a function with the returned data instead of just storing it in a global variable, and heed their advice. That is the only way you will succeed in solving the problem. You can use a callback, or you can use a promise - those are simply two ways of doing the same thing. What you can't do is just store the data in a global variable and expect it to be available after you issue the ajax request. – Michael Geary Commented Jul 19, 2015 at 5:14
  • 1 I updated one of your fiddles to turn it into a working example: jsfiddle/mea2nr7t/1 – Michael Geary Commented Jul 19, 2015 at 5:23
  • 2 What you can't do is "return" the data or leave it behind in a global variable or the like. Here's the problem with that: How will your code that needs the data know when it has actually been received from the server? The only way to know that the data is ready is when the callback has been called. – Michael Geary Commented Jul 19, 2015 at 5:40
 |  Show 3 more ments

5 Answers 5

Reset to default 4

I would tend to favor a promise here:

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/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);
    });
});

Here it is in action: http://jsfiddle/MarkSchultheiss/7bmnsvay/

function getVisitorData(callback) {
    $.ajax({
        type: "GET",
        url: "http://freegeoip/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);
});

Do the data manipulation in callback function not in any other function. For more info visit Callback function

Create a global object.

Var objMyData={};

Store ip and country code in that object.

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

Now pass objMyData object as a parameter to any function.

I do not know why you need to return an array in your callback.As ajax is asynchronous, it will not wait till the response es, it will execute the rest of the statements. So return value will give you undefined. You can use/assign the response only after response es.

function getVisitorData(callback) {
    return $.ajax({
        type: "GET",
        url: "http://freegeoip/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.");
    });
});

This is the mon problem lot of us are not knowing is, before your service call success or failure, the line next to your service call will execute, So you need to set some timeout

//Create a global object. var objMyData = {}global object;

function getVisitorData() {function call $.ajax({`ajax type: "GET", url: "http://freegeoip/json/", dataType: "json", async: true, success: function (response) { //Store ip and country code in that object. objMyData.ip = response.ip; objMyData.Country = response.country_code; }, error: function (response) { alert("IP thing didn't work."); } }); }

jQuery(document).ready(function () { //Now pass objMyData object as a parameter to any function. getVisitorData();method call setTimeout(function(){ console.log(objMyData); }, 500); });

发布评论

评论列表(0)

  1. 暂无评论