Javascript function return not working

I have a problem returning a variable in my function, the below script works fine:

function sessionStatus(){
    $(document).ready(function(){
        $.getJSON(scriptRoot+"sessionStatus.php",function(status){
            alert(status);
        });
    });
}

sessionStatus();

Bet, when I try the following, I get a window with the message "undefined":

function sessionStatus(){
    $(document).ready(function(){
        $.getJSON(scriptRoot+"sessionStatus.php",function(status){
            return status;
        });
    });
}
alert(sessionStatus());

It really bothers me, I just can’t understand what I did wrong.

+3
source share
7 answers

You need to know two things:

1: The JSON thing is asynchronous, so the call to the sessionStatus function can already be done when the JSON is still being retrieved. The following would be done:

function sessionStatus(callback){
    $(document).ready(function(){
        $.getJSON(scriptRoot + "sessionStatus.php", function(status){
                callback(status);
        });
    });
}
sessionStatus(function(s){alert(s);});

or rather:

function sessionStatus(callback){
    $(document).ready(function(){
        $.getJSON(scriptRoot + "sessionStatus.php", callback);
    });
}
sessionStatus(function(s){alert(s);});

2: , , sessionStatus . ( JSON):

function do() {
    var x = 0;
    (function(){
       x = 2;
    })();
    return x;
}

function do() {
    var x = (function(){
       return 2;
    })();
    return x;
}

2. , .

+10

sessionStatus() , undefined.

, AJAX - sessionStatus(), .

function(status) { ...} , AJAX , AJAX .

, $.getJSON() $(document).ready(), , .

+2

sessionStatus() . , -, sessionStatus()

+1

, . ? jQuery , .

+1

sessionStatus $(document).ready(), . undefined.

, $(document).ready(), ajax, , , .

+1
function sessionStatusCallback(status)
{
    alert(status);
}

function sessionStatus(){
    $(document).ready(function(){
        $.getJSON(scriptRoot+"sessionStatus.php",function(status){
                sessionStatusCallback(status);
        });
    });
}

sessionStatus();

- , .ready() .getJSON(). , , , .

, , getJSON , . "sessionStatusCallback", , JSON , . ... ( , .getJSON())

+1

Functions should never be included in the jQuery (document) .ready function. Separate them, so you have no side effects that you do not want to have. What do you want to name the session status? And should the witch function get the return value?

0
source

Source: https://habr.com/ru/post/1722830/


All Articles