Ajax时间间隔调用php函数

时间:2012-05-25 15:03:20

标签: php ajax

我有一个调用php文件的ajax代码:

function ajaxRequest(){
var requestData; 

try{
    // Opera 8.0+, Firefox, Safari
    requestData = new XMLHttpRequest();
} catch (e){
    // IE
    try{
        requestData = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            requestData = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
            // Your browser is brokeded.
            alert("Please try again later!");
            return false;
        }
    }
}
// Send/receive data
requestData.onreadystatechange = function(){
    if(requestData.readyState == 4){
        document.getElementById("testDiv").innerHTML = requestData.responseText;
    }
}
requestData.open("GET", "tester.php", true);
requestData.send(null); }

我真正想要的代码是按时间间隔在同一页面上调用php函数。我打算在向mysql数据库中的表添加新行时显示通知。如果以上情况不合适,请帮我编辑此代码或者可能是新代码。我将感谢你的帮助。谢谢

2 个答案:

答案 0 :(得分:3)

我建议你使用jQuery,这是一个提供多种功能的js框架。您的代码示例如下:


        function callMe()
        {
            $.ajax({
                   type: "GET",
                   url: "test.php",
                   data: "id=1",
                   success: function(response){
                              $("#testDiv").html(response);
                            }
           });
        }

    // Call it
    setInterval(callMe, 5000); //every 5 secs

答案 1 :(得分:1)

<script>
       function callMe()
        {
            $.ajax({
                   type: "GET",
                   url: "count.php",
                   data: "id=1",
                   success: function(response){
                              $("#Count").html(response);
                            }
           });
        }

    // Call it 
    // "setInterval" means every 5 secs 
    // "setTimeout" just once...

    setInterval(callMe, 5000); 
</script>  

<p>Count:<span id="Count"></span></p>