2013-04-09 49 views
1

我有一個與php進行通信以接收來自twitter帳戶的推文的ajax。代碼工作正常。 唯一的問題是我想讓ajax間歇性地調用php,以便任何更新後的tweets自動回來並打印到我的頁面,而不必刷新或重新輸入twitter id。 我需要繼續調用getStatuses()函數嗎? 或者我需要使用getUpdates(),我已經開始做些什麼? 這裏是我的ajax功能:如何獲得ajax間歇性地調用我的php?

// 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?

回答

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 
+0

只是增加了一個setInterval函數,沒有看到完整的答覆。我現在就看看它。 – user1835504 2013-04-09 23:34:47

+0

'callback && callback'是做什麼的? – user1835504 2013-04-09 23:36:35

+0

感謝它的幫助,我會接受它。對不起,我不是很擅長編碼,只是學習。發現難以遵循你的建議。我試圖實現它,但它沒有奏效。 – user1835504 2013-04-10 00:14:31