刚才发生了什么?
下面就是比较有趣的部分。你将理解在那些代码里发生了什么。让我们从用户首先交互的文件,index.html,开始。这个文件引用了一个神奇的名为quickstart.js的JavaScript文件,并且建立了一个非常简单的客户端交换。
下面的代码片断是取自index.html,注意下用粗体标出的元素。
<body onload='process()'>
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage" />
</body>
当页面装载的时候,quickstart.js中一个名为process()的函数就会被执行。这以某种方式引起<div>元素被服务器上的消息填充。在看process()函数内部发生了什么之前让我们看看在服务器内发生了什么。在服务器上,你有一个名为quickstart.php的脚本。它用来创建发往客户端的XML消息。这个XML消息包含一个<response>元素。这个元素封装了服务器发往客户端的消息:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
... message the server wants to transmit to the client ...
</response>
如果从客户端获取的信息是空的,那么返回的信息就是“Stranger,please tell me your name!”。如果名字是Cristian,Bogdan,Filip,Mihai或者Yoda,服务器返回“Hello,master<user name>!”。如果是其他的,那么消息就是“<user name>,I don't know you!”。所以如果Mickey Mouse输入它的名字,那么服务器返回的如下的XML结构:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
Mickey Mouse, I don't know you!
</response>
quickstart.php脚本的开头产生XML文档的头和<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>';
加粗的部分把输出标记为XML文档,这很重要。因为客户端期待接受XML(如果头没有设置Content-Type为text/xml,那么客户端解析XML的API会抛出一个错误)。在设置头之后,代码就开始连接字符串生成XML响应。实际要返回给客户端的信息被封装在<response>元素内。这是个根元素。<response>元素里的信息是基于客户端通过GET参数传来的名字:
// 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>';
?>
用户输入的内容(假定是用户的名字)通过使用GET参数从客户端传送到服务器端。当把这个信息回传给客户端时,我们使用了PHP里的函数htmlentities来取代HTML代码里的特殊字符(如&,>),以确保在浏览器里能够安全地显示这些信息,消除潜在的问题和安全风险。
注意:
在服务器端为客户端格式化信息(而不是直接在客户端来做)在编写商业代码时实际上是个不好的做法。一般来讲,服务器的职责就是以普通的格式发送数据,而由接受端来处理安全和格式化事务。如果你想某一天你要往数据库中插入完全相同的信息,但是数据库需要不同的格式化的序列(在这种情况下,应该由数据库来格式化数据而不是服务器),这样似乎更有意义。对于quickstart,在PHP中格式化HTML可以使得我们保持代码简短,易于理解和解释。
如果你好奇,想测试quickstart.php看看它产生了什么,你可以在你的浏览器里装载http://localhost/ajax/quickstart/quickstart.php?name=Yoda。在客户端通过GET传递参数的好处是在你的浏览器它可以简单地产生个类似的请求,因为GET只是意味着你在URL查询字符串中附加了name/value这么一对参数。你将得到类似下面的东西:
这个XML消息在客户端通过quickstart.js的handleServerResponse()方法处理。更明确地说,是下面几行代码提取了“Hello,master Yoda”消息:
// 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;
这里xmlHttp是XMLHttpRequest的对象,用来在客户端调用服务器上的quickstart.php脚本文件。它的responseXML属性处理得到的XML文档。XML的结构天然就是层次的。XML文件的根元素被称为文档元素。在我们这个例子中,文档元素是<response>元素,它只包含了一个子元素,就是我们感兴趣的文本信息。一旦获取了这个文本信息,那么它将被显示在客户页面上,即通过DOM(Document Object Model)来访问index.html里的divMessage元素实现:
// update the client display using the data received from the server
document.getElementById('divMessage').innerHTML = helloMessage;
document是JavaScript里的默认对象,允许你对页面的HTML代码里的元素进行操作。
quickstart.js里的其他代码用来向服务器产生请求以或得XML消息。createXmlHttpRequestObject()方法创建并返回XMLHttpRequest对象。这个方法要比它本来的要长些,这是因为我们要保持它对各个浏览器兼容。XMLHttpRequest的实例,即xmlHttp在process()方法里被使用以向产生服务器产生异步请求:
// 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);
}
更多内容请看PCdog.com--Ajax的WEB开发 Ajax技术 Ajax技术核心专题
