为什么body onload = javascript函数连续执行?

时间:2012-08-15 16:58:06

标签: javascript ajax onload

很抱歉这个真正的新手问题,刚刚开始学习AJAX。

我想了解以下内容究竟是什么导致divMessage内容在" myName"文字改变了。

1)似乎Javascript函数进程经常" listen",这是正常的Javscript行为,还是有任何触发器调用" process"反复? 2)我们分配给" body onload"是否正确?将被重复执行?这种重复执行的频率是多少? 3)如果我们想要一次执行函数过程怎么办?

4)我很困惑,因为我认为身体只会加载一次。但这是因为" body onload"功能"过程"被调用,功能过程反过来修改" body"通过改变divMessage,基本上让它通过" 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>';
?>

1 个答案:

答案 0 :(得分:0)

通过关闭并尝试再次运行来找到答案。 事实证明,我注释了其他代码 但缓存了每1秒从handleServerResponse()调用“进程”:

// display the data received from the server
    document.getElementById("divMessage").innerHTML =
              '<i>' + helloMessage+ '</i>';
    setTimeout('process()', 1000);

很抱歉。课程是在测试每个代码更改之前清除浏览器缓存:) 所以我想检查是否从任何其他地方调用此函数的建议是正确的。 无论如何,我读了很多东西,并在尝试计算时学到了很多东西 这个。非常感谢@pst!