Javaphua Blog

BlogJava 首页 新随笔 联系 聚合 管理
  46 Posts :: 5 Stories :: 46 Comments :: 0 Trackbacks

Ajax 基础和例子

Ajax -- Asynchronous JavaScript and XML Ajax 使用的是JavaScript + DOM + CSS + XMLHttpRequest的技术,是目前Web2.0更加流行的技术.

与传统网络应用相比,Ajax具备更加直观和方便的用户交互. 为什么呢? 比如, 我们需要点击链接或按钮来激发事件,而使用Ajax只要移动鼠标或者在一个输入框输入字母已经可以触发事件. 传统的网络应用是基于page-driven的模式, 使用的是'click, wait a refresh the whole page' 模式, 而Ajax是通过data-driven的模式来提供网络页面的, 采用的是部分页面更新的模式, 页面中只更新有新数据的部分,其它的部分依然不变,所以依然可以操作.

Ajax就象它的名字一样, 可以异步地在浏览器和服务器之间进行交流, 当服务器端处理submit过来的数据的同时, 客户依然可以正常地处理浏览器端同一页面的其他功能.

那么Ajax和传统网络应用相比是怎样工作的呢?下面这张图可以让你了解清楚.

传统的网络应用在浏览器和服务器之间的交流是直来直去的, 而Ajax的网络应用在浏览器中有一个Ajax引擎,这个引擎实际上就是一个Javascript的对象XMLHttpRequest, 而XMLHttpRequest负责浏览器和服务器的异步交流.

XMLHttpRequest既然是Javascript的对象, 当然需要一些Javascript的代码来生成, 它目前支持大部分的浏览器,包括了Mozilla, Firefox等等.

服务器端依然可以使用传统的技术如servlet, JSP, JSF,Struts等等,但会有一些小的限制,比如客户端会发更频繁的请求,而响应这些请求的类型包括text/xml, text/plain, text/json, text/javascript.

整个Ajax的操作过程分为七步:

1.A client event occurs

2.An XMLHttpRequest object is created

3.The XMLHttpRequest object is configured

4.The XMLHttpRequest object makes an async. request

5.The ValidateServlet returns an XML document containing the result

6.The XMLHttpRequest object calls the callback() function and processes the result

7.The HTML DOM is updated

我们分别来看看这七个步骤是怎么做的: 1. A client event occurs,

<input type="text"
size="20"
id="userid"
name="id"
onkeyup="validateUserId();">

比如我们手头上有这样一段Javascript的代码:  这是一个ID为userid的文本框,里面包含了一个Javascript的函数,当我们在文本框里打入一个英文字母时,会激发onkeyup的事件,从而激发validateUserId的Javascript的函数.

2.An XMLHttpRequest object is created

var req;
function initRequest() {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function validateUserId() {
initRequest();
req.onreadystatechange = processRequest;
if (!target) target = document.getElementById("userid");
var url = "validate?id=" + escape(target.value);
req.open("GET", url, true);
req.send(null);
}

validateUserId的Javascript的函数调用initRequest函数生成XMLHttpRequest对象, 大家注意到在initRequest函数里面有两种生成XMLHttpRequest的方法,这是针对不同的浏览器的做法,对于Mozilla,我们可以直接使用"new XMLHttpRequest()”, 而对于IE,我们需要生成ActiveX对象.

3.The XMLHttpRequest object is configured

rvalidateUserId的Javascript的函数包含一句req.onreadystatechange = processRequest; 这是通过设定XMLHttpRequest对象里面的onreadystatechange特性为回调函数.

4.The XMLHttpRequest object makes an async. request

if (!target) target = document.getElementById("userid");
var url = "validate?id=" + escape(target.value);
req.open("GET", url, true);
req.send(null);

然后XMLHttpRequest调用open方法和服务器交流, open方法有三个参数, HTTP方法是Get还是Post, 服务器端的URL, 方式采取异步还是同步.

5.The ValidateServlet returns an XML document containing the result

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String targetId = request.getParameter("id");
if ((targetId != null) && !accounts.containsKey(targetId.trim())) {
response.setContentType("text/xml ");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<valid>true</valid>");
} else {
response.setContentType("text/xml ");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<valid>false</valid>");
}
}

然后是服务器端ValidateServlet的响应,首先Content type设为text/xml, Cache-Control设为no-cache, 最后会返回true或者false的xml格式响应.

6.The XMLHttpRequest object calls the callback() function and processes the result

function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
var message = ...;

现在控制交回给客户端, 由于我们设定了回调函数为processRequest, 那么当响应从服务器端回到客户端浏览器,就激发了processRequest函数, 我们在processRequest函数中检查XMLHttpRequest对象的readyState状态是否为4和status状态是否为200,如果两者同时成立,就代表服务器端的数据已经成功返回给客户端,那么就可以执行下面的处理.

 7.The HTML DOM is updated.

接收完服务器端传回来的数据后,浏览器开始着手显示接收回的数据.

我们通过页面里面的<div>元素来唯一的表示一个对象给DOM的API使用. 比如确定html页面某一处的需要显示的信息文本对象,我们可以使用userIdMessage唯一的标签来做引用给DOM的API使用. 如下面这段代码:

23.<body>
24. <div id="userIdMessage"></div>
25.</body>

一但你有了唯一确定的引用,你就可以使用DOM的API对其进行随心所欲的操作,如属性的修改等等,比如下面这段代码:

1. <script type="text/javascript">
2. function setMessageUsingDOM(message) {
3. var userMessageElement = document.getElementById("userIdMessage");
4. var messageText;
5. if (message == "false") {
6. userMessageElement.style.color = "red";
7. messageText = "Invalid User Id";
8. } else {
9. userMessageElement.style.color = "green";
10. messageText = "Valid User Id";
11. }
12. var messageBody = document.createTextNode(messageText);
13. // if the messageBody element has been created simple replace it otherwise
14. // append the new element
15. if (userMessageElement.childNodes[0]) {
16. userMessageElement.replaceChild(messageBody,
17. userMessageElement.childNodes[0]);
18. } else {
19. userMessageElement.appendChild(messageBody);
20. }
21.}
22.</script>
23.<body>
24. <div id="userIdMessage"></div>
25.</body>

在这里javascript通过了getElementById方法得到了userIdMessage对象,然后对服务器端返回的数据进行对比,如果值是true,在userIdMessage里添加文本"Valid User Id", 如果值是false,则在userIdMessage里添加文本"Invalid User Id".

大概就是这样的一个状况,那么在Ajax里面的XMLHttpRequest还有很多方法和属性, 包括:

方法:


• open(“HTTP method”, “URL”, syn/asyn)
> Assigns HTTP method, destination URL, mode
• send(content)
> Sends request including string or DOM object data
• abort()
> Terminates current request
• getAllResponseHeaders()
> Returns headers (labels + values) as a string
• getResponseHeader(“header”)
> Returns value of a given header
• setRequestHeader(“label”,”value”)
> Sets Request Headers before sending

属性:

• onreadystatechange
> Set with an JavaScript event handler that fires at each
change
• readyState – current status of request
> 0 = uninitialized
> 1 = loading
> 2 = loaded
> 3 = interactive (some data has been returned)
> 4 = complete
• status
> HTTP Status returned from server: 200 = OK

• responseText
> String version of data returned from the server
• responseXML
> XML document of data returned from the server
• statusText
> Status text returned from server

 

posted on 2007-08-13 09:31 Javaphua 阅读(387) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: