Javascript div 刷新

Javascript div refresh

我正在尝试刷新 php 脚本以将更新的内容显示为数据库更新。我首先构建了我的 php,然后刷新代码,然后合并它们。但是,脚本不会更新。有人知道为什么吗?

<script type="text/javascript"
    src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
    $(document).ready(
            function() {
                setInterval(function() {
                    if(document.getElementById('gallery') != null){
                        function showLots() {
                            if (window.XMLHttpRequest) {
                                // code for IE7+, Firefox, Chrome, Opera, Safari
                                xmlhttp = new XMLHttpRequest();
                            } else {
                                // code for IE6, IE5
                                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                            }
                            xmlhttp.onreadystatechange = function() {
                                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                                    document.getElementById("gallery").innerHTML = xmlhttp.responseText;
                                }
                            }
                        xmlhttp.open("GET","getuser.php",true);
                        xmlhttp.send();
                        } 
                    }
                }, 3000);
            });
</script>

谢谢。

你没有调用方法showLots,首先在函数外定义它,然后在setInterval

中调用它

您的代码存在的问题是 function showLots() 在您的 if (document.getElementById('gallery') != null) 条件语句中,而函数并未实际执行。

下面是将 function showLots() 定义上移后更正后的代码可能的样子。 showLots() 然后在你最初定义的地方被调用。

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
    function showLots() {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("gallery").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","getuser.php",true);
        xmlhttp.send();
    } 

    $(document).ready(function () {
        setInterval(function () {
            if (document.getElementById('gallery') !== null) {
                showLots();
            }
        }, 3000);
    });
</script>