快速进入Ajax开发的实例解说(1)(4)
在服务器端为客户端格式化信息(而不是直接在客户端来做)在编写商业代码时实际上是个不好的做法。一般来讲,服务器的职责就是以普通的格式发送数据,而由接受端来处理安全和格式化事务。如果你想某一天你要往数据库中插入完全相同的信息,但是数据库需要不同的格式化的序列(在这种情况下,应该由数据库来格式化数据而不是服务器),这样似乎更有意义。对于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; |
| // 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); } |






