2015-06-27 25 views
2

我正在使用ajax,以便我可以從我的服務器讀取文件的內容。我正在調用一個函數,其中ajax是,在一個timer.And這是影響我的服務器。它是如果這是正確的做法,那有什麼問題? 請給予幾個sugestions,因爲我不知道它的問題是什麼。定時器中的Ajax影響我的服務器

我首先調用函數:「function(ctrl)」。

function get(ctrl){ 
    var content; 
     content=ctrl.id; 

     var getTextUpdate= setInterval(function() { 
        readdocument(); 
     }, 1200); 

} 

function readdocument() { 
     var xmlhttp; 
     if (window.XMLHttpRequest){ 
       xmlhttp=new XMLHttpRequest(); 
     }else{ 
       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
       xmlhttp.onreadystatechange=function(){ 
        if (xmlhttp.readyState==4 && xmlhttp.status==200) 
        { 
          document.getElementById("area").value=xmlhttp.responseText; 
        } 
       } 
     xmlhttp.open("GET","../user/test/read-text.php?user="+content,true); 
     xmlhttp.send(); 

} 

這是讀text.php文件:

<?php 
    $rec_user=$_GET['user']; 
    echo($rec_user); 
    $chat = fopen($rec_user.".txt", "r") or die("Unable to open file!"); 
    echo fread($chat,filesize($rec_user.".txt")); 
    fclose($chat); 
?> 
+1

爲什麼不使用jQuery或一些已經在Js框架中構建的Ajax? –

回答

4

與您的代碼的問題是,你是不是等待響應渡過。所以在那個時候,你會在請求後發送請求。這將在適當的時候耗盡所有內存。因此,請在發送下一個請求之前先等待響應。

這個怎麼樣?

function loadXMLDoc(ctrl) { 
    var content=ctrl.id; 
    var xmlhttp = new XMLHttpRequest(); 
    var url = "../user/test/read-text.php?user="+content; 

    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == XMLHttpRequest.DONE) { 
      if (xmlhttp.status == 200) { 
       document.getElementById("area").value=xmlhttp.responseText; 
       setTimeout(loadXMLDoc(), 1200); //call the function again 
      } else if (xmlhttp.status == 400) { 
       console.log('There was an error 400'); 
      } else { 
       console.log('something else other than 200 was returned'); 
      } 
     } 
    }; 

    xmlhttp.open("GET", url, true); 
    xmlhttp.send(); 
}; 

loadXMLDoc(ctrl); 
+0

:在閱讀你的帖子時,我觀察到了一些東西,我沒有得到它。什麼是內容?你寫了這樣的東西:「setTimeout(content(),1200); //再次調用函數」。它是一個函數?還有一件事。因爲你刪除了函數get(ctrl),我必須調用函數loadXMLDoc嗎? –

+0

對不起,這是一個錯字。它不是'content','loadXMLDoc'。是的,現在不用'get(ctrl)',你現在應該使用函數'loadXMLDoc'。但是,您可以根據您的命名約定重新命名該函數。 –

+0

謝謝你的幫助! –

相關問題