How can I use variable outside the function?

时间:2015-09-01 21:56:42

标签: javascript jquery

$('#liveUpdate').click(


        $.getJSON("http://freegeoip.net/json/", function(data) {
            var country = data.country_name;
            var ip = data.ip;
        });

        alert(country);

    });

I wanted to use country outside getJSON but not the correct result. Tried to define variable top of the click function but not resolved my problem.

How can I fix it?

1 个答案:

答案 0 :(得分:-1)

Change your approach to work with the asynchronous nature of ajax.

Say you wanted to use country in a function

function someFunction(country){
    //country used here
}

Then call it within the success callback of the ajax

$('#liveUpdate').click(function(){
        $.getJSON("http://freegeoip.net/json/", function(data) {
            country = data.country_name;
            var ip = data.ip;
            someFunction(country);
        });

    });