我試圖把一個非常簡單的彗星測試頁。我有一個div ID爲#TextHistory的主客戶端頁面。這個頁面中的javascript應該創建一個到backend.php的開放連接,它使用javascript來更新一個值並將其刷新回客戶端頁面。我真的不確定我是否正確地執行了此操作...我已將其基於How do I implement basic "Long Polling"?。長輪詢/彗星PHP後端不沖洗正確的數據 - 新手問題
我發現的是在客戶端頁面(FireFox),它看起來像backend.php 10秒後沒有返回任何東西和超時。如果我在backend.php中取出php循環,constanty會返回「DefaultData」並直接附加到TextHistory DIV。我覺得我很接近但做錯了什麼。對不起,這裏有奇怪的格式,它看起來像一些標題和PHP標籤是不允許的。
客戶端:
$(document).ready(function() {
waitForMsg(); /* Start the inital request */
});
function addmsg(type, msg){
/* Simple helper to add a div.
type is the name of a CSS class (old/new/error).
msg is the contents of the div */
$("#TextHistory").append(
"<div class='msg "+ type +"'>New MSG: "+ msg +"</div>"
);
}
function waitForMsg(){
/* This requests the url "msgsrv.php"
When it complete (or errors)*/
$.ajax({
type: "GET",
url: "backend.php",
async: true, /* If set to non-async, browser shows page as "Loading.."*/
cache: false,
timeout:50000, /* Timeout in ms */
success: function(data){ /* called when request to barge.php completes */
addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
setTimeout(
'waitForMsg()', /* Request next message */
1000 /* ..after 1 seconds */
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
'waitForMsg()', /* Try again after.. */
"15000"); /* milliseconds (15seconds) */
},
});
};
</script>
</head>
<body>
<div id="container">
<div id="main">
<h2>Text Scrolling Test</h2>
<div id="TextHistory">
<p>First default line of text</p>
<p>Second default line of text</p>
</div>
</div>
</div>
</body>
</html>
Backend.php被稱爲:
<---php start --->
session_start();
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 2012 05:00:00 GMT");
flush();
<---php end --->
那麼默認的HTML文檔類型,頭部,元,jQuery的包括
然後在身體:
<div id="LastMsg">DefaultData</div>
<---PHP Start --->
$OutputMsg = "Initial";
while (true) {
$OutputMsg .= "Something.";
echo "
<script type=\"text/javascript\">
$('#LastMsg').html(\"<p>$OutputMsg</p>\");
</script>
";
flush(); // Ensure the Javascript tag is written out immediately
sleep(1);
}
<---PHP END --->
它是否有可能在服務器後端運行javascript/jQuery? 此外,...這只是一個測試,所以我可以得到一個處理彗星的東西如何工作,這是不真實的應用程序的真實世界。我讚賞意見,建議不要這樣做。 – 2011-01-28 11:23:26