How to make javascript variable global

2020-03-13 08:55发布

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?

2条回答
家丑人穷心不美
2楼-- · 2020-03-13 09:19

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,

    // ....
});
查看更多
Animai°情兽
3楼-- · 2020-03-13 09:21

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.

查看更多
登录 后发表回答