1

我有 ajax 与 php 通信以接收来自 Twitter 帐户的推文。代码工作正常。唯一的事情是我希望 ajax 间歇性地调用 php,以便任何更新的推文自动返回并打印到我的页面,而无需刷新或重新输入推特 ID。我需要继续调用 getStatuses() 函数吗?或者我是否需要使用我已经开始制作的 getUpdates() ?这是我的ajax函数:

 // the setInterval function added in the getStatusesX function
function getStatusesX()
{
setInterval(getStatuses(),300000);
}

  //Create a cross-browser XMLHttp Request object
function getXMLHttp() {

    var xmlhttp;
    if (window.ActiveXObject) {
        XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } else if (window.XMLHttpRequest) {
       XMLHttp = new XMLHttpRequest();
    } else {
        alert("Your browser does not support XMLHTTP!");
    }
    return XMLHttp;
}

 //function that searches for the tweets via php
function getStatuses(){

      XMLHttp1 = getXMLHttp();
      var userID = document.getElementById("userid").value;

      //ajax call to a php file that will extract the tweets
      XMLHttp1.open( 'GET', 'twitterTest2.php?userid='+userID, true);

      // Process the data when the ajax object changes its state
      XMLHttp1.onreadystatechange = function() {
         if( XMLHttp1.readyState == 4 ) {
            if( XMLHttp1.status ==200 ) {  //no problem has been detected

         document.getElementById("tweetbox").innerHTML=XMLHttp1.responseText;

            }
         }
       }
       XMLHttp1.send(null);
}

//function to intermittently call php to check for updated tweets?
function updateInfo() { 
    if(XMLHttp1.readyState == 4) { 

        document.getElementById("tweetbox").innerHTML=XMLHttp1.responseText;

    } 
}

</script>

然后我将 getStatusesX() 函数添加到我的表单中,如下所示:

<form>
Input Twitter ID: <input type="text" name="userid" id="userid">  
<button type="button" onClick="getStatusesX()";>Get recent  tweets</button>
</form> 

它仍然无法正常工作。我是否以错误的方式使用 setInterval?

4

1 回答 1

3

使用setTimeoutsetInterval功能。

从我在你的代码中可以看到,getStatuses有太多的责任,因为除了获取数据之外,它还修改了DOM.

我会建议类似:

function getStatuses(callback) {
    //...
    XMLHttp1.onreadystatechange = function () {
        //...
        callback && callback(XMLHttp1); //execute callback if any
    };
}

function updateStatuses(callback) {
    getStatuses(function (xhr) {
        document.getElementById("tweetbox").innerHTML = xhr.responseText;
        callback && callback;
    });
}

//this function update the statuses and as soon as it's finished, it sets
//a timeout to redo the process in ~10 seconds.
function startUpdatingStatuses() {

    updateStatuses(function () {
        setTimeout(startUpdatingStatuses, 10000);
    });
}

startUpdatingStatuses(); //kick-start everything
于 2013-04-09T22:52:39.900 回答