您的位置:首页 > 其它

Ajax入门到精通(一)

2009-09-28 13:33 260 查看
Ajax 由 HTML、JavaScript™ 技术、DHTML 和 DOM 组成

1. 创建新的 XMLHttpRequest 对象

var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
//非IE浏览器支持
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}


2. 发出 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.jsp?city=" + escape(city) + "&state=" + escape(state);
// Open a connection to the server
xmlHttp.open("GET", url, true);
// Setup a function for the server to run when it's done
xmlHttp.onreadystatechange = updatePage;
// Send the request
xmlHttp.send(null);
}


open方法:其中指定了连接方法(GET)和要连接的 URL。最后一个参数如果设为
true
,那么将请求一个异步连接(这就是 Ajax 的由来)。如果使用
false
,那么代码发出请求后将等待服务器返回的响应。如果设为
true
,当服务器在后台处理请求的时候用户仍然可以使用表单(甚至调用其他 JavaScript 方法)。

open()方法的5个参数:

open()
:建立到服务器的新请求。

send()
:向服务器发送请求。

abort()
:退出当前请求。

readyState
:提供当前 HTML 的就绪状态。

responseText
:服务器返回的请求响应文本。

onreadystatechange
属性:告诉服务器在运行完成 后(可能要用五分钟或者五个小时)做什么。因为代码没有等待服务器,必须让服务器知道怎么做以便您能作出响应。在这个示例中,如果服务器处理完了请求,一个特殊的名为
updatePage()
的方法将被触发。

send()方法:
因为已经在请求 URL 中添加了要发送给服务器的数据(city 和 state),所以请求中不需要发送任何数据。这样就发出了请求,服务器按照您的要求工作。

如果需要发送安全信息或 XML,可能要考虑使用
send()
发送内容

3. 处理服务器响应

function updatePage() {
if (xmlHttp.readyState == 4&&xmlHttp.status == 200) {
var response = xmlHttp.responseText;
document.getElementById("zipCode").value = response;
}
}


xmlHttp.readyState 属性的值:返回服务器响应状态

0:请求没有发出(在调用
open()
之前)。

1:请求已经建立但还没有发出(调用
send()
之前)。

2:请求已经发出正在处理之中(这里通常可以从响应得到内容头部)。

3:请求已经处理,响应中通常有部分数据可用,但是服务器还没有完成响应。

4:响应已完成,可以访问服务器响应并使用它。

xmlHttp.status 检查 HTTP 状态,我们期望的状态码是 200

401:未经授权

403:禁止

404:没找到

200:一切正常

xmlHttp.responseText
属性,服务器将把响应填充到responseText 属性中

4. 启动一个 Ajax 过程

<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>


5.使用 Ajax 生成一个 HEAD 请求

function getSalesData() {
createRequest();
var url = "/boards/servlet/UpdateBoardSales";
request.open("HEAD", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}


获取响应的长度
request.getResponseHeader("Content-Length");


获取内容类型
request.getResponseHeader("Content-Type");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: