跟“无为”学习Ajax技术第二天

第二天:Ajax 世界中的请求/响应原理
我分三个小章节讲:发出请求、处理响应、连接表单
发出请求
您已经有了一个崭新的 XMLHttpRequest 对象,现在让它干点活儿吧。首先需要一个 Web 页面能够调用的 JavaScript 方法(比如当用户输入文本或
者从菜单中选择一项时)。接下来就是在所有 Ajax 应用程序中基本都雷同的流程: (掌握对写代码易如反掌)
(1)从 Web 表单中获取需要的数据。
(2)建立要连接的 URL。
(3)打开到服务器的连接。
(4)设置服务器在完成后要运行的函数。
(5)发送请求。
发送Ajax请求的代码如下:(实际上是一样函数^_^函数重要性可想而知)
function callServer() {
// Get the city and state from the web form
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
// Only go on if there are values for both fields
if ((city == null) || (city == "")) return;
if ((state == null) || (state == "")) return;
// Build the URL to connect to
var url = "/scripts/getZipCode.php?city=" + escape(city) + "&state=" + escape(state); //注意这里是的url,当然也可以是asp、aspx、jsp
// Open a connection to the server
xmlHttp.open("GET", url, true); //请求一个异步连接;若为false,代码发出后请求Server返回响应。
// Setup a function for the server to run when it's done
xmlHttp.onreadystatechange = updatePage; //告诉服务器下一步做什么
// Send the request
xmlHttp.send(null);
}
处理响应
现在要面对服务器的响应了。只要知道两点:
(1)什么也不要做,直到 xmlHttp.readyState=4。
(2)服务器将把响应填充到 xmlHttp.responseText 属性中。
其中的第一点,即就绪状态。第二点,使用 xmlHttp.responseText 属性获得服务器的响应,这很简单。
处理服务器响应代码如下:
function updatePage() {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
document.getElementById("zipCode").value = response;
}
}
连接表单
<form>
<p>City: <input type="text" name="city" id="city" size="25"
onChange="callServer();" /></p>
<p>State: <input type="text" name="state" id="state" size="25"
onChange="callServer();" /></p>
<p>Zip Code: <input type="text" name="zipCode" id="city" size="5" /></p>
</form>
如果感觉这像是一段相当普通的代码,那就对了,正是如此!当用户在 city 或 state 字段中输入新的值时,callServer() 方法就被触发,于是 Ajax 开始运行了。

posted on 2007-12-03 14:20  CodeShark  阅读(400)  评论(0编辑  收藏  举报

导航