简体   繁体   中英

How to use and reuse JS variables across functions

I have a situation where I need to initialize/assign variables from the results of a jQuery AJAX call, and then re-use those variables further on down the script:

var shouldRedirect = ???

$.ajax({
    url: 'http://example.com',
    type: 'GET',
    data: 'blah',
    asynch: false,
    timeout: 1800,
    success: function(data) {
        shouldRedirect = data.rows[0].redirectFlag
    }
});

if(shouldRedirect)
    window.location = "...";

Two issues I'm having:

  • Assuming the resultant JSON will contain a redirectFlag boolean, is data.rows[0].redirectFlag the proper way of obtaining the value for my variable?; and
  • What do I initialize shouldRedirect to before the AJAX is kicked off (how do I say "create a variable but don't give it a value yet!")?

Thanks in advance!

You can declare uninitialized variables by simply doing the following:

var shouldRedirect;

If your logic requires it you can of course initialize it to false:

var shouldRedirect = false;

This might not be what you desire though. You can check if a variable was initialized by strictly comparing it to undefined :

if (shouldRedirect === undefined) // do something

Note though, that you must use the triple equal operator (aka strict equality) or your results will not be as expected. On the other side, an undefined variable will yield a falsy result. This means that when checking a variable with a simple if (shouldRedirect) and the variable is undefined then it will yield false , as if it was set to false. This is also true for a couple of other values in JavaScript, eg the empty string "" or the value null . You can see a complete list of falsy values here . If you want to check explicitly for true or false and want to omit other falsy or truthy values, then you should check with triple equality, eg if (shouldRedirect === true) .

Also, if data.rows[0].redirectFlag is the correct way to access the value is highly dependend on how the data structure you receive from your AJAX call actually looks like. If it is something like the following it would be correct:

{ rows: [ {redirectFlag: true}, {redirectFlag: false} ] }

If your JSON looks like the following though

{ redirectFlag: false }

then you have to access redirectFlag simply with data.redirectFlag .

  • What do I initialize shouldRedirect to before the AJAX is kicked off (how do I say "create a variable but don't give it a value yet!")?

    You could just do: var shouldRedirect;

However, I would do var shouldRedirect = false; to ensure shouldRedirect is not undefined

  • Is data.rows[0].redirectFlag the proper way of obtaining the value for my variable?

Depends what you send back from the AJAX request. Usually responses are in JSON so if you send a JSON object back with a value true then you could do:

shouldRedirect = data.redirectFlag;

For part #1 to declare a variable with it having a value use: var shouldRedirect. This way you can just do a if (!shouldRedirect) {}.

For part #2. How to get the value from redirectFlag is based on the formation of the data returned from the ajax call. data... would be the starting point for you to get the value.

As mentioned in the comments section, setting the shouldRedirect flag isn't going to help as the if statement that follows the $.ajax request will be evaluated before the result is fetched from the server - this is a common problem faced in asynchronous code execution. Although you can, in theory, force jQuery.ajax into syncronous mode via the sync parameter, I wouldn't recommend doing so as it will lock up the browser UI whilst the request is made.

You need to move your redirection code into the $.ajax success function like so:

$.ajax({
    url: 'http://example.com',
    // ... other options omitted for brevity

    success: function(data) {
        // This code block gets executed when the operation completes.
        var shouldRedirect = data.rows[0].redirectFlag
        if (shouldRedirect) {
            // Your redirection code goes here.
            window.location = "...";
        }
    }
});

If you using of jQuery 1.7 or greater, you can make use their Promises/A implementation via the defered object . Defered object's allow you to execute one or more functions when an operation completes and makes the async code easier to read.

$.ajax({ url: 'http://example.com' })
    .done(function(data) { 
        // This code block gets executed when the operation completes.
    });

Instead of passing a function closure to done , you can also pass a reference to a member function, eg:

$.ajax({ url: url }).done(onDataLoaded);

function onDataLoaded(data) {
    // This function gets called when the ajax operation completes.
}

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