AJAX分析

Ajax的原理:
Ajax 应用程序所用到的基本技术:
? HTML 用于建立 Web 表单并确定应用程序其他部分使用的字段。 
? JavaScript 代码是运行 Ajax 应用程序的核心代码,帮助改进与服务器应用程序的通信。 
? DHTML 或 Dynamic HTML,用于动态更新表单。我们将使用div、span和其他动态 HTML 元素来标记 HTML。 
? 文档对象模型 DOM 用于(通过 JavaScript 代码)处理 HTML 结构和(某些情况下)服务器返回的 XML。 
一般的 Web 应用程序:
在一般的 Web 应用程序中,用户填写表单字段并单击 Submit 按钮。然后整个表单发送到服务器,服务器将它转发给处理表单的脚本(通常是 PHP 或 Java,也可能是 CGI 
进程或者类似的东西),脚本执行完成后再发送回全新的页面。该页面可能是带有已经填充某些数据的新表单的 HTML,也可能是确认页面,或者是具有根据原来表单中输入数
据选择的某些选项的页面。当然,在服务器上的脚本或程序处理和返回新表单时用户必须等待。屏幕变成一片空白,等到服务器返回数据后再重新绘制。这就是交互性差的原因
,用户得不到立即反馈,因此感觉不同于桌面应用程序。
Ajax程序:
Ajax 基本上就是把 JavaScript 技术和XMLHttpRequest对象放在 Web 表单和服务器之间。当用户填写表单时,数据发送给一些 JavaScript 代码而不是直接发送给服务器
。相反,JavaScript 代码捕获表单数据并向服务器发送请求。同时用户屏幕上的表单也不会闪烁、消失或延迟。换句话说,JavaScript 代码在幕后发送请求,用户甚至不知
道请求的发出。更好的是,请求是异步发送的,就是说 JavaScript 代码(和用户)不用等待服务器的响应。因此用户可以继续输入数据、滚动屏幕和使用应用程序。然后,
服务器将数据返回 JavaScript 代码(仍然在 Web 表单中),后者决定如何处理这些数据。它可以迅速更新表单数据,让人感觉应用程序是立即完成的,表单没有提交或刷
新而用户得到了新数据。
 
/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
 xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
 try {
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
 } catch (e2) {
    xmlHttp = false;
 }
}
@end @*/
 
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
 xmlHttp = new XMLHttpRequest();
}

XMLHttpRequest对象的创建:
1.       建立一个变量xmlHttp来引用即将创建的XMLHttpRequest对象。
2.       尝试在 Microsoft 浏览器中创建该对象:
o        尝试使用Msxml2.XMLHTTP对象创建它。
o        如果失败,再尝试Microsoft.XMLHTTP对象。
3.       如果仍然没有建立xmlHttp,则以非 Microsoft 的方式创建该对象。
最后,xmlHttp应该引用一个有效的XMLHttpRequest对象,无论运行什么样的浏览器。

 Ajax 应用程序中基本都雷同的流程:
1.       从 Web 表单中获取需要的数据。
2.       建立要连接的 URL。
3.       打开到服务器的连接。
4.       设置服务器在完成后要运行的函数。
5.       发送请求。
例如:
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);
 
 // 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);
}
 

处理响应
现在要面对服务器的响应了。现在只要知道两点:
? 什么也不要做,直到xmlHttp.readyState属性的值等于 4。 
? 服务器将把响应填充到xmlHttp.responseText属性中。 
其中的第一点,即就绪状态,第二点,使用xmlHttp.responseText属性获得服务器的响应
function updatePage() {
 if (xmlHttp.readyState == 4) {
    var response = xmlHttp.responseText;
    document.getElementById("zipCode").value = response;
 }
}

XMLHttpRequest 对象方法 
方法 描述
abort() 停止当前请求
getAllResponseHeaders() 作为字符串返问完整的headers
getResponseHeader("headerLabel") 作为字符串返问单个的header标签
open("method","URL"[,asyncFlag[,"userName"[, "password"]]]) 设置未决的请求的目标 URL, 方法, 和其他参数
send(content) 发送请求
setRequestHeader("label", "value") 设置header并和请求一起发送
  XMLHttpRequest 对象属性 
属性 描述
onreadystatechange 状态改变的事件触发器
readyState 对象状态(integer):
0 = 未初始化
1 = 读取中
2 = 已读取
3 = 交互中
4 = 完成
responseText 服务器进程返回数据的文本版本
responseXML 服务器进程返回数据的兼容DOM的XML文档对象
status 服务器返回的状态码, 如:404 = "文件末找到" 、200 ="成功"
statusText 服务器返回的状态文本信息 
 
 
例如:针对登陆页面功能
index.js
//创建XMLHttpRequest
function createXMLHttpRequest() {
 if (window.XMLHttpRequest) {
  XMLHttpReq = new XMLHttpRequest();
 } else {
  if (window.ActiveXObject) {
   try {
    XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
   }
   catch (e) {
    try {
     XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e) {
    }
   }
  }
 }
}

//载入Request的url
function loadRequest(url) {
 createXMLHttpRequest();
 XMLHttpReq.open("GET", url, true);
 XMLHttpReq.onreadystatechange = processLoadResponse;
 XMLHttpReq.send(null);
}
 
//处理载入的状态
function processLoadResponse() {
 if (XMLHttpReq.readyState == 4) {
  if (XMLHttpReq.status == 200) { // 信息已经成功返回,开始处理信息
   AddBlogList();
   AddArticleList();
  } else { //页面不正常
   window.alert("你所请求的页面有异常");
  }
 }
}

//登陆处理反应状态,
function processLoginResponse()
{
  if (XMLHttpReq.readyState == 4) {
  if (XMLHttpReq.status == 200) { // 信息已经成功返回,开始处理信息
   var res=XMLHttpReq.responseXML.getElementsByTagName("res")[0].firstChild.nodeValue;
   if(res ==1)
   {
    window.alert('用户名错误');
   }
   else if(res ==2)
   {
    window.alert('密码错误');
   }
   else if(res ==3)
   {
    window.alert('验证码错误');
   }
   else if(res ==0)
   {
    var id = XMLHttpReq.responseXML.getElementsByTagName("id")[0].firstChild.nodeValue;
    window.open("openBlog.do?blogId="+id+"&operate=toArticle");
   }
  } else { //页面不正常
   window.alert("你所请求的页面有异常");
  }
 }
}
 

列表的显示,放在response种 用out输出:
  response.setContentType("text/xml; charset=UTF-8");
  response.setHeader("Cache-Control", "no-cache");
  // 创建输出流对象
  PrintWriter out = response.getWriter();
  // 依据验证结果输出不同的数据信息
  out.println("<response>");
  /*
   * 输出热点博客
   */
  for (int i = 0; i < blogList.size(); i++) {
   Blog curBlog = (Blog) blogList.get(i);
   out.println("<blog>");
   out.println("<id>" + curBlog.getId() + "</id>");
   out.println("<name>" + curBlog.getSubject() + "</name>");
   out.println("</blog>");
  }
  out.println("</response>");
  out.close();
页面部分显示,在js种实现:
function AddBlogList() {
 deleteBlogList();
 var xmlDoc = XMLHttpReq.responseXML;
 var blogs = xmlDoc.getElementsByTagName("blog");
 var currentBlog = null;
 for (var i = 0; i < blogs.length; i++) {
  currentBlog = blogs[i];
  var id = currentBlog.getElementsByTagName("id")[0].firstChild.nodeValue;
  var name = currentBlog.getElementsByTagName("name")[0].firstChild.nodeValue;
  
  var row = document.createElement("tr");
  row.setAttribute("id", id);
  
  var cell = document.createElement("td");
  cell.appendChild(document.createTextNode("NO " + (i + 1) + "."));
  row.appendChild(cell);
  
  cell = document.createElement("td");
  var href = document.createElement("a");
  href.setAttribute("href", "openBlog.do?blogId=" + id+"&operate=toArticle");
  href.appendChild(document.createTextNode(name));
  cell.appendChild(href);
  row.appendChild(cell);
  
  document.getElementById("blogList").appendChild(row);
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值