如何使用jQuery或Ajax在10秒间隔内刷新一个div

3

非常感谢您的提问。这里有一个问题需要您的帮忙:我正在使用Yii MVC框架构建一个PHP Web应用程序,并且该框架具有许多内置工具。正如标题所说,我需要每10秒刷新一次div。目前,我已经拥有了以下Ajax函数:

<script type="text/javascript">
    function ajaxFunction(){
    var ajaxRequest;  

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function(){
                var list = document.getElementById('logged_in_users_list');
        if(ajaxRequest.readyState == 4){
            list.innerHTML = ajaxRequest.responseText;
                        setTimeout('ajaxFunction()',10000);
        }
    }
    ajaxRequest.open("GET", "protected/controllers/room/openRoom", true);
    ajaxRequest.send(null);
}
</script>


<script type="text/javascript">
            setInterval(function() {ajaxFunction();}, 5000);
</script>

对于那些不熟悉Yii的人来说,它将大部分php文件存储在一个名为protected的文件夹中。上面的ajaxRequest.open代码行请求存储在protected文件夹内的url,因此我一直收到403访问被禁止的错误。有什么想法可以用jquery实现不同的方法或解决这个访问问题吗?
3个回答

6
使用jQuery
$(function() {
    function callAjax(){
        $('#myDiv').load("http://yourdomain.com");
    }
    setInterval(callAjax, 5000 );
});

3
您的代码在jQuery中的大致等价物如下所示:

以下是需要翻译的内容:

//execute call immediately
(function check(){
    //a GET AJAX call
    $.get('protected/controllers/room/openRoom')
    .done(function(data){
        //when we receive, populate
        $('#logged_in_users_list').html(data);
    })
    .always(function(){
        //regardless of a fail or success, call again after 10 seconds
        setTimeout(check,10000);
    });
}());

403错误代码始终是403。这个代码告诉你,你无权进入该位置(也许你需要进行身份验证?)。


1
    // zisu.php

    <html>
    <head>
    <script type="text/javascript">
    var auto_refresh = setInterval(
           function ()
           {
           $('#div1').load('time.php');
           }, 10000);
    </script>
    </head>
    <body>
    <div id ="div1">
    <?php
    echo date("h:i:s A");
    ?>
    </div>
    </body>
    </html>


// time.php
    <?php
    echo date("h:i:s A");
    ?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接