简体   繁体   中英

How to make javascript variable global

I need to make this data variable global:

$.ajax({
    url: "get_data.php",
    cache: false,
    dataType: 'json',
    data: {},
    success: function(data) {
        for(var i = 0; i < data.results.length; i++) {
            if(my_data.hasOwnProperty(data.results[i].id)) {
                my_data[data.results[i].id].name = data.results[i].name;
            }
        }
    });

I want to have this globally declared. Do I need to declare it as array?

Any variable can be "made global" by attaching it as a property of the window.

window.data = data;

You can now access data as a global variable.

Set a variable equal to what you wish data to be equal to. And when giving data its value, reference the variable. Like this:

var obj = {};

$.ajax({
    // ....

    data: obj,

    // ....
});

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