简体   繁体   中英

Access javascript global variable

Following is my JavaScript. How do I make the variable success global so that the changes made in ajax->success are reflected outside?

function foo() {  
    var success = false;  
    $.ajax({

        type: "POST",
        url: "",
        dataType: "xml",
        success: function(xml) {
            var code = parseInt($(xml).find("Response").attr("code"), 10);
            switch (code) {
                case 1:
                    success = false;
                    break;
                case 0:
                    success = true;
                    break;
            }
        }
    });
    return success;
}

Pass a callback function that is called in the success :

function makeCall(callback) {
    $.ajax({
        type: "POST",
        url: "",
        dataType: "xml",
        success: function(xml) {
            var code = parseInt($(xml).find("Response").attr("code"), 10);
            callback(!code);
        }
    });
}

makeCall(function (success) {
    alert(success);
});

This is how asynchronous programming/requests work. Of course, the alternative is to make it a synchronous request, but kind of defeats the purpose.

I condensed the switch stuff because you seemed to want the opposite boolean values of 0 and 1 .

The approach you are after will not work. The Ajax call is asynchronous. Meaning it will return immediately even before the actual GET is fired. So the outer var (which is accessible from inside the success callback, thanks to closures) won't have any value other than the one established before the Ajax call by the time it is returned. Instead you can specify that the Ajax call fire synchronously, by setting async:false along with the other values in the $.ajax, or you can restructure the code to do whatever you wanted to do if the function returned true by putting it 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