全局var,正确的方法或任何解决方法? (在DOM准备好之前)

时间:2016-02-11 12:34:55

标签: javascript

一直试图在javascript中设置全局变量以便从另一个函数访问,
但是有一个我无法访问的特定全局变量,它返回null 如果我在函数本身声明var,它就有效。

注意:我无法使用任何js库。

这不起作用:

var xhttp = new XMLHttpRequest(); <-- this works as the request in the function runs.
var DialogBody = document.getElementById("DialogBody");//<-- this is the problem

function fetchDialog() {
    url = "../message/user_status.php";
    xhttp.open('POST',url,true);
    xhttp.send();
    xhttp.onreadystatechange = function() {
        if(xhttp.readyState == 4 && http.status == 200) {
            showOverlay();
            console.log("OK");// returns ok.
            /*below all return error*/
            DialogBody.innerHTML = "TEST";//<-- error: Cannot set property 'innerHTML' of null
        }
    }   
}

这有效:

function fetchDialog() {
    url = "../message/user_status.php";
    var DialogBody = document.getElementById("DialogBody");     
    xhttp.open('POST',url,true);
    xhttp.send();
    xhttp.onreadystatechange = function() {
        if(xhttp.readyState == 4 && http.status == 200) {
            showOverlay();
            console.log("OK");// returns ok.            
            DialogBody.innerHTML = "TEST";//This works.
        }
    }   
}   

所以我的问题是,如何将var设置为全局而不是函数。

编辑:(由SO用户提供的链接解决。)&lt; - 不是我想要的。

var xhttp = new XMLHttpRequest();
var DialogBody;
document.addEventListener("DOMContentLoaded", function(event) {
DialogBody = document.getElementById("DialogBody ");
});

function fetchDialog() {
    url = "../message/user_status.php";
    xhttp.open('POST',url,true);
    xhttp.send();
    xhttp.onreadystatechange = function() {
        if(xhttp.readyState == 4 && http.status == 200) {
            showOverlay();
            //console.log("OK");
            DialogBody.innerHTML = "TEST";
        }
    }   
}

更新:(我真正想要的。)

有点不那么漂亮的解决方法是这个虽然它可能会皱眉头。 我实际想要实现的是设置全局变量(合并) 我最终使用eval()将那些var设置为字符串来实现我想要的东西,我觉得它非常有用。

javascript概念

/.....
var xhttp = new XMLHttpRequest();
DialogBody = 'document.getElementById("DialogBody")';
//or DialogBody = 'document.getElementById("DialogBody").innerHTML';

function fetchDialog() {
    url = "../message/user_status.php";
    xhttp.open('POST',url,true);
    xhttp.send();
    xhttp.onreadystatechange = function() {
        if(xhttp.readyState == 4 && http.status == 200) {
            showOverlay();
            //console.log("OK");
            eval(DialogBody).innerHTML="Test";
            //or eval(DialogBody) = "a message that is dynamically generated";
            //eval(DialogBody).className="Whatever";
        }
    }   
}

实际情况。

user_status.php

//..query ends.
<div id="DialogTitleMessage">
    <?php echo $DialogTitle;?>
</div>
<div id="DialogBodyMessage">
    <?php echo $DialogTitle;?>
</div>

实际的javascript

//.....
var xhttp = new XMLHttpRequest();
DialogBody = 'document.getElementById("DialogBody")';
DialogTitle = 'document.getElementById("DialogTitle")';
DialogTitleMessage = 'document.getElementById("DialogTitleMessage")';

function fetchDialog() {
    url = "../message/user_status.php";
    xhttp.open('POST',url,true);
    xhttp.send();
    xhttp.onreadystatechange = function() {
        if(xhttp.readyState == 4 && http.status == 200) {
            showOverlay();
            eval(DialogBody).innerHTML = xhttp.responseText;
            eval(DialogTitle).innerHTML = eval(DialogTitleMessage).innerHTML;
        }
    }   
}

4 个答案:

答案 0 :(得分:0)

你需要在加载DOM时执行getElementById,试试这个:

window.onload = function() {
    window.DialogBody = document.getElementById("DialogBody");
};

答案 1 :(得分:0)

var DialogBody; //Declaring

window.onload = function() {
    DialogBody = document.getElementById("DialogBody"); //Intializing
};    

function fetchDialog() {
        url = "../message/user_status.php";
        xhttp.open('POST',url,true);
        xhttp.send();
        xhttp.onreadystatechange = function() {
            if(xhttp.readyState == 4 && http.status == 200) {
                showOverlay();
                DialogBody.innerHTML = "TEST"; //Use here
            }
        }   
    }

答案 2 :(得分:0)

尝试将var放在document.addEventListener函数中:

document.addEventListener("DOMContentLoaded", function(event) { 
    var DialogBody = document.getElementById("DialogBody");
    fetchDialog();
});

var DialogBody;
document.addEventListener("DOMContentLoaded", function(event) { 
     DialogBody = document.getElementById("DialogBody")
    fetchDialog();
});

而不是

window.onload = function() {
    DialogBody = document.getElementById("DialogBody"); //Intializing
};

因此var将在文档加载后声明。

window.onload和document.addEventListener之间的区别在于,当只能使用一次window.onload时,可以使用多次document.addEventListener。

另外只是为了让您知道window.onload将在加载窗口后处于活动状态(图像,视频...),并且在加载文档后document.addEventListener将处于活动状态。

答案 3 :(得分:0)

试试这个:

window.onload = function() {
window.DialogBody = document.getElementById("DialogBody");
};

或者这个:

    var DialogBody;// by declaring this variable globally you can access it anywhere and also can avoid scope conflicts

    function fetchDialog() {
    url = "../message/user_status.php";
    DialogBody = document.getElementById("DialogBody");     
    xhttp.open('POST',url,true);
    xhttp.send();
    xhttp.onreadystatechange = function() {
        if(xhttp.readyState == 4 && http.status == 200) {
            showOverlay();
            console.log("OK");// returns ok.            
            DialogBody.innerHTML = "TEST";//This works.
        }
    }   
}