使用jQuery获取会话值

I would like to retrieve data from a session variable on a button click, without reloading the page. My getter function is the following one:

function GetSession()
{
    var value;

    function GetValue(data)
    {
        value = data;
    }

    $.get("sessionAPI.php?action=get", function(data) { GetValue(data); });
    return value;
}

Yet the "value" variable stays undefined after I call this function. How could I give the value of "data" to the "value" variable? Thanks for the answers!

You are trying to return a value from an asynchronous operation (i.e. that completes later). That will never work as it returns long before the result is available. You need to use callbacks or promises instead.

Using a callback the code looks like:

function GetSession(callback)
{
    $.get("sessionAPI.php?action=get", function(data) { callback(data); });
}

and use like this:

GetSession(function(value){
  // Do something with the session value
});

Using promises:

function GetSession()
{
    return $.get("sessionAPI.php?action=get");
}

and use like this:

GetSession().done(function(value){
  // Do something with the session value
});