刚才发生了什么?
下面就是比较有趣的部分。你将理解在那些代码里发生了什么。让我们从用户首先交互的文件,index.html,开始。这个文件引用了一个神奇的名为quickstart.js的JavaScript文件,并且建立了一个非常简单的客户端交换。下面的代码片断是取自index.html,注意下用粗体标出的元素。
<body >
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage" />
</body>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
... message the server wants to transmit to the client ...
</response>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
Mickey Mouse, I don't know you!
</response>
<?php
// we'll generate XML output
header('Content-Type: text/xml');
// generate XML header
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
// create the <response> element
echo '<response>';
// retrieve the user name
$name = $_GET['name'];
// generate output depending on the user name received from client
$userNames = array('CRISTIAN', 'BOGDAN', 'FILIP', 'MIHAI', 'YODA');
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!';
// close the <response> element
echo '</response>';
?>
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseXML;
// obtain the document element (the root element) of the XML structure
xmlDocumentElement = xmlResponse.documentElement;
// get the text message, which is in the first child of
// the document element
helloMessage = xmlDocumentElement.firstChild.data;
// make asynchronous HTTP request using the XMLHttpRequest object
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);
}
else
// if the connection is busy, try again after one second
setTimeout('process()', 1000);
}