有一個小的網頁從Web服務器請求XML文件。 Web服務器每秒更新一次該文件,並在網頁上顯示新數據。重複的AJAX請求緩慢的瀏覽器
頁面運行一段時間後,每當它從服務器獲取新數據(每秒兩次)時,它會減慢整個瀏覽器的速度。問題是間歇性的 - 有時會持續幾秒鐘,有時會持續更長時間。
這個問題存在於Firefox中。
function getData() {
var dataVal = parseFloat($("#data").html().substring(0, 100));
doSomethingWithVal(XTEval); // seemingly irrelevant, as it lags without this function too
}
t = 0.5;
function process_xml() {
var xmlhttp = GetXmlHttpObject();
if (xmlhttp === null) {
alert("Your browser does not support AJAX!");
return;
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
document.getElementById("data").innerHTML = xmlhttp.responseText;
getData();
setTimeout('process_xml()', t * 1000); // moved from end of function to here based on a suggestion
}
};
xmlhttp.open("GET", "data.shtml", true);
xmlhttp.send("");
}
function GetXmlHttpObject() {
if (window.XMLHttpRequest)
return new XMLHttpRequest();
if (window.ActiveXObject)
return new ActiveXObject("Microsoft.XMLHTTP");
return null;
}
data.shtml只包含:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--#echo var="someVal.val" -->
或許有比使用AJAX不同/更好的辦法?
在這個函數中用'var'聲明你的「xmlhttp」變量是個好主意。沒有這個,它是一個全局變量,並且連續調用「process_xml」並覆蓋其先前的值。 – Pointy 2014-12-02 17:33:24
謝謝!我不知道這一點,而且我已經做出了改變。我繼承了這些代碼,並且一直在慢慢更新它。 – 2014-12-02 17:40:22
我說得對,getData不在你的代碼中,getXTE不是從process_xml調用的嗎?你可以證實這一點或修復你的例子(其中可能包括修復XTEVal和dataVal) – rene 2014-12-02 20:43:04