對不起,真正新手的問題,剛開始學習AJAX。爲什麼body onload = javascript函數連續執行?
我想了解下列原因導致divMessage內容在「myName」文本更改時不斷更改。 1)Javascript函數過程似乎在不斷「聽」,這是正常的Javscript行爲,還是有觸發器重複調用「過程」? 2)我們分配給「body onload」的任何函數是否會重複執行?這種重複執行的頻率如何? 3)如果我們想單個執行函數過程,該怎麼做?
4)我很困惑,因爲我認爲身體只會加載一次。但這是因爲在「body onload」之後調用了函數「process」,函數進程又通過改變divMessage來修改「body」,實質上讓它再次通過「body onload」,然後再「處理」等等。?
非常感謝您的幫助!
<head>
<script type="text/javascript" src="quickstart.js"></script>
</head>
<body onload='process()'>
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage" />
</body>
這裏的quickstart.js加工零件
function process()
{
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
// retrieve the name typed by the user on the form
name = encodeURIComponent(
document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send(null);
}
}
// callback function executed when a message is received from the server
function handleServerResponse()
{
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4)
{
// status of 200 indicates the transaction completed successfully
if (xmlHttp.status == 200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
helloMessage = xmlDocumentElement.firstChild.data;
// display the data received from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage+ '</i>';
}
}
}
和quickstart.php
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo '<response>';
$name = $_GET['name'];
// generate output depending on the user name received from client
$userNames = array('YODA', 'AUDRA', 'BOGDAN', 'CRISTIAN');
if (in_array(strtoupper($name), $userNames))
echo 'Hello, master ' . htmlentities($name) . '!';
else if (trim($name) == '')
echo 'Stranger, please tell me your name!';
else
echo htmlentities($name) . ', I don't know you!';
echo '</response>';
?>
它(文檔加載事件)應該只執行一次,除了一些瀏覽器的怪癖(舊的IE和iframe?)。我知道如果重新打開文檔對象(如document.write)應該重新觸發它,但DOM操作(即使'innetHTML')通常不應該..或者我可能已經使用jQuery這麼長時間了,我忘記了如何破碎很簡單,IDK。 – 2012-08-15 17:03:10
在任何情況下,請使用瀏覽器標記這是觀察。 – 2012-08-15 17:04:05
請參閱:http://stackoverflow.com/questions/5418216/ajax-triggering-bodys-onload-event(也許)。或者,從其他任何位置調用進程?(除onload之外)? – 2012-08-15 17:15:16