人在江湖

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  82 Posts :: 10 Stories :: 169 Comments :: 0 Trackbacks

Ajax是一组技术的集合:javascript, css, DOM, XMLHttpRequest.

其中XMLHttpRequest是达到异步效果的核心部件。

一个异步的例子,摘自Ajax in Action:

   1: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   2: "http://www.w3.org/TR/html4/loose.dtd">
   3: <html>
   4: <head>
   5: <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
   6: <title>无标题文档</title>
   7: <script type="text/javascript">
   1:  
   2: var req=null;
   3: var console=null;
   4: var READY_STATE_UNINITIALIZED=0;
   5: var READY_STATE_LOADING=1;
   6: var READY_STATE_LOADED=2;
   7: var READY_STATE_INTERACTIVE=3;
   8: var READY_STATE_COMPLETE=4;
   9: function sendRequest(url,params,HttpMethod)
  10: {
  11:    if(!HttpMethod)
  12:    {
  13:      HttpMethod="GET";
  14:    }
  15:    req=initXMLHTTPRequest();
  16:    if(req)
  17:    {
  18:       req.onreadystatechange=onReadyState;
  19:       req.open(HttpMethod,url,true);
  20:       req.setRequestHeader("Content-Type","appplication/x-www-form-urlencoded");
  21:       req.send(params);
  22:    } 
  23: }
  24:  
  25: function initXMLHTTPRequest()
  26: {
  27:   var xRequest=null;
  28:   if(window.XMLHttpRequest)
  29:   {
  30:      xRequest=new XMLHttpRequest();
  31:   }
  32:   else if(window.ActiveXObject)
  33:   {
  34:      xRequest=new ActiveXObject("Microsoft.XMLHTTP");
  35:    }
  36:    return xRequest;
  37:   
  38: }
  39:  
  40: function onReadyState()
  41: {
  42:   var ready=req.readyState;
  43:   var data=null;
  44:   if(ready==READY_STATE_COMPLETE)
  45:   {
  46:      data=req.responseText;
  47:   }
  48:   else
  49:   {
  50:      data="loading...["+ready+"]";
  51:   }
  52:   toConsole(data);
  53:   
  54: }
  55:  
  56: function toConsole(data)
  57: {
  58:   if(console!=null)
  59:   {
  60:      var newline=document.createElement("div");
  61:      console.appendChild(newline);
  62:      var txt=document.createTextNode(data);
  63:      newline.appendChild(txt);
  64:   }
  65: }  
  66:   window.onload=function()
  67:   {
  68:     console=document.getElementById("console");
  69:     sendRequest("data.txt"");
  70:   }
  71:  
</script>
   8: </head>
   9:  
  10: <body>
  11: <div id="console">aaa</div>
  12:  
  13: </body>
  14: </html>

注意其中 req.onreadystatechange=onReadyState;就是定义了callback handler

以后需要关注的一些方面:

DWR: http://directwebremoting.org/dwr/index.html 适合后端为Java的应用. DWR和jQuery是可以混合使用的。

JSON:它可以取代异步调用传输的xml

posted on 2011-03-16 15:54 人在江湖 阅读(364) 评论(0)  编辑  收藏 所属分类: UI & MVC

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


网站导航: