Ajax to read PHP


Ajax to read PHP

我想我超越了自己,但我尝试了 AJAX 教程来读取 PHP 文件。PHP文件只有一个时间的echo语句,我想传递它来初始化javascript时钟。

但这是我第一次尝试 AJAX,我什至无法让它激活测试警报消息。

这是代码,它位于所有PHP之后的PHP页面底部。

<script type='text/javascript'>
function CheckForChange(){
    //alert("4 and 4");
    //if (4 == 1){
        //setInterval("alert('Yup, it is 1')", 5000);
        //alert('Now it is changed');
    //}
    var ajaxReady = new XMLHttpRequest();
    ajaxReady.onreadystatechange = function(){
        if (ajaxReady.readystate == 4){
            //Get the data
            //document.getElementById('clocktxt').innerHTML = ajaxReady.responseText;
            alert("here");
            alert(ajaxReady.responseText);
        }
    }
    ajaxReady.open("GET","ServerTime.php",true);
    ajaxReady.send(null);
}
setInterval("CheckForChange()", 7000);
</script>

有人可以告诉我为什么这不起作用吗?不知道我做错了什么。

代码中的问题是未大写的字母。 (哎呀! 你检查ajaxReady.readystate;您需要检查ajaxReady.readyState.

由于ajaxReady.readystate始终未定义,因此警报永远不会触发。

这是您的代码已修复并正常工作。


顺便说一句,您是否考虑过使用库来处理跨浏览器XHR的丑陋之处? jQuery是你的朋友:

function CheckForChange(){
    $.get('ServerTime.php', function(data) {
        $('#clocktxt').text(data);
    });
}

您可能应该有这样的东西:

setInterval(CheckForChange, 7000);

在一个不相关的说明中,JavaScript 中常见的命名约定是函数和方法名称的首字母不大写,其余的都在 camelCase 中。 checkForChange() .

我不确定你的代码的确切问题;这是我使用的 - 我相信它会为你工作。(另外,它适用于更多浏览器)

var xhr = false;
function CheckForChange(){
    /* Create xhr, which is the making of the object to request an external file */
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    }else{
        if(window.ActiveXObject){
            try {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }catch(e){}
        }
    }
    /* End creating xhr */
    /* Retrieve external file, and go to a function once its loading state has changed. */
    if(xhr){
        xhr.onreadystatechange = showContents;
        xhr.open("GET", "ServerTime.php", true);
        xhr.send(null);
    }else{
        //XMLHTTPRequest was never created. Can create an alert box if wanted.
    }
    /* End retrieve external file. */
}
function showContents(){
    if(xhr.readyState==4){
        if(xhr.status==200){
            alert(xhr.responseText);
        }else{
            //Error. Can create an alert box if wanted.
        }
    }
}
setInterval(CheckForChange, 7000);