简体   繁体   中英

how to set and return a variable inside JavaScript function?

see the example first then you can understand my question.

var x;
function checkTime() {
    $.ajax({ 
        type: 'GET', 
        url: 'http://www.example.com/time.php', 
        data: test,
        dataType:'json',
        success: function (data) {
            if (data == 0){
                x = 'true';
            } else if (data == 1){
                x = 'false';
            }
        }
    });
}

checkTime();
alert (x);

the alert will be undefined

I need to set x inside the checkTime functions and grab it outside the function

even if i do :

var x = checkTime();
alert (x);

i still get undefined

also i only need to check for true or false, maybe there is another way to do things. I also tried:

...
if (data == 0){
    return true;
} else if (data == 1){
    return false;
}
...

but i don't know how to check for that.

basically i need to so something like :

if (x == 1){ // if(x == true) //do something }

any ideas?

thanks

This happens because the default behaviour of .ajax() is asynchronous . x will not have been set by the time your alert() fires. You either need to set the .ajax() with aync=false or pass in a callback function to call when your Ajax request has completed, eg

function checkTime(callback) {
    $.ajax({ 
        type: 'GET', 
        url: 'http://www.example.com/time.php', 
        data: test,
        dataType:'json',
        success: function (data) {
            var x = '';
            if (data == 0){
                x = 'true';
            } else if (data == 1){
                x = 'false';
            }
            // Call the callback function with 'x'
            callback.call(null, x);
        }
    });
}

And then use it like follows:

checkTime(function (x) {
    alert(x);
});

It happens because AJAX is asynchronous. When your code reaches alert, the success function of AJAX request does not executed yet. You can try to set ajax request to async:false, or make alert inside of success function.

You cannot directly access the return value of the function defined for the "success"; first you should know that two functions are involved here: checkTime , and the unnamed event handler function for the success event of the ajax call. You want to retrieve a value out of that unnamed event handler function; that function is however not called directly from checkTime , but when the AJAX request returns (it's event-driven programming : the function (data) {...} is executed when the event AJAX call succeeded happens).

In your example, the alert you call after executing checkTime will usually be called before the AJAX request is finished; this is because the AJAX request happens asynchronously , and therefore the event that the call succeeded need not have happened yet. If you always want to wait for the answer to the request, you can disable the asynchronicity of the AJAX call (async:false); but maybe you can also do the distinction what you want to do directly in the event handler instead of outside. That would be the way to go for if you want to follow event-driven programming paradigm.

If you want to continue doing something else while the request is running, your options would also include eg using some other (eg global) variable for the "return value" of the success function AJAX call (and possibly a second for indicating whether the call is finished), and checking periodically if it has been set yet (but that would not follow the event-driven programming paradigm, and might be considered bad practice since it unnecessary frequent polling of a variable is needed).

It happens because checkTime() returns immediately, before the success function is executed. The success function doesn't execute until after the ajax call is complete, so x is not set yet when you try to use it.

Depending on what you are trying to accomplish, you could put the alert inside the success callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM