Javascript Ajax总结

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 15:49   2872   0

通过Ajax技术,浏览器可以和服务器建立通道进行数据交换并且可以在不重新载入页面的情况下更新页面的局部内容。

建立Ajax通信的步骤:

1.创建一个XMLHttpRequest对象。

2.调用的XMLHttpRequest的open方法初始化对象,设置数据的发送方式(GET/POST),URL等。

3.使用send方法将请求发送到服务器。

4.请求发送到服务器后,根据请求对象的状态触发回调函数,获取响应。

下面依次实现以上各个步骤:

一.创建XMLHttpRequest对象。

主流浏览器(FireFox,Chrome,Opera,Safari)支持XMLHttpRequest对象,IE例外,从IE7才开始支持,但是之前支持的是ActiveX对象,因此创建的时候要确保兼容性。

function createRequestObject() {
  var ajaxRequest;
  try {
    ajaxRequest = new XMLHttpRequest();
  } catch(e) {
    //ie浏览器
    try {
      ajaxRequest = new ActiveXObject("Msxm12.XMLHTTP");
    } catch(e) {
      try {
         ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
         return false;
      }
    }
  }
  return ajaxRequest;
}

XMLHttpRequest的属性

status:请求响应的状态码

statusText:以字符串形式返回的Http状态码,比如OK和NOT FOUND

readyState:代表当前XMLHttpRequest对象状态的数字

0:已创建XMLHttpRequest对象,没有初始化

1:加载中,还没有调用send方法

2:已经加载,已经调用send方法

3:交互中,收到部分数据

4:交互完成,所有数据都已经接收并且可用

responseText:服务器返回的字符串

responseXML:服务器返回的xml对象

方法:

abort():取消请求

getAllResponseHeaders():得到http头信息

getResponseHeader(str):得到指定http头的值,比如Server或者Last-Modified

open():初始化XMLHttpRequest对象

setRequestHeader():增加消息头

事件处理函数:

onreadystatechange:当readyState改变时回调

onerror:请求过程中发生错误时回调

onprogress:内容加载后回调

onload:文档加载完成后回调

二.初始化XMLHttpRequest对象

调用open方法初始化,open的3个参数分别是:请求类型(POST/GET),url以及参数,是否异步请求

get示例:

 ajaxRequest.open("GET","http://localhost:8080/test?name=tim", true);
 ajaxRequest.send(null);

post示例:

 ajaxRequest.open("POST","http://localhost:8080/test", true);
 ajaxRequest.sendRequestHeader("Content-Type", "application/x-www-form-urlencoded")
 ajaxRequest.send("name=tim");
三.监听服务器响应

将处理函数赋值给回调函数onreadystatechange,它在请求结束时被回调。

 ajaxRequest.onreadystatechange=function() {
  .......
 }
四.获取服务器响应内容

 ajaxRequest.onreadystatechange=function() {
    if (ajaxRequest.readyState==4) {
      if (ajaxRequest.status==200) {
        var txtObj = ajaxRequest.responseText;
      }
    }
 }
下面示例演示一个完整的ajax请求过程

服务端Servlet:

@WebServlet("/AjaxServlet")
public class AjaxServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  //返回表单中的输入
  String name = request.getParameter("name");
  String age = request.getParameter("age");
  response.getWriter().write("name="+name+";age="+age);
  response.getWriter().close();
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doGet(request, response);
 }
}

JSP:

<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
<script type="text/javascript">
function createRequestObject() {
   var ajaxRequest;
   try {
     ajaxRequest = new XMLHttpRequest();
   } catch(e) {
     //ie浏览器
     try {
       ajaxRequest = new ActiveXObject("Msxm12.XMLHTTP");
     } catch(e) {
       try {
          ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
       } catch (e) {
          return false;
       }
     }
   }
   return ajaxRequest;
 }
 //get方式
 function goAjaxWithGet() {
  var ajaxRequest = createRequestObject(); 
  if (ajaxRequest != false) {
   ajaxRequest.onreadystatechange = function() {
    if (ajaxRequest.readyState==4) {
     if (ajaxRequest.status==200) {
      alert(ajaxRequest.responseText);
     }
    } else if (ajaxRequest.status==404) {
     alert("找不到");
    }
   }
  }
  var name = encodeURIComponent(document.getElementById("name").value);
  var age = encodeURIComponent(document.getElementById("age").value);
  
  ajaxRequest.open("GET", "http://localhost:8080/FirstStruts/AjaxServlet?name="+name+"&age="+age, true);
  ajaxRequest.send(null);

 }
 //post方式
 function goAjaxWithPost() {
  var ajaxRequest = createRequestObject(); 
  if (ajaxRequest != false) {
   ajaxRequest.onreadystatechange = function() {
    if (ajaxRequest.readyState==4) {
     if (ajaxRequest.status==200) {
      alert(ajaxRequest.responseText);
     }
    } else if (ajaxRequest.status==404) {
     alert("找不到");
    }
   }
  }
  var name = encodeURIComponent(document.getElementById("name").value);
  var age = encodeURIComponent(document.getElementById("age").value);
  ajaxRequest.open("POST", "http://localhost:8080/FirstStruts/AjaxServlet", true);
  ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  ajaxRequest.send("name="+name+"&age="+age);
 
 }
   
</script>

</head>
<body>
   <form action="">
        name:<input type="text" id="name" value="oHeHeHou" /><br/>
        age:<input type="text" id="age" value="12" /><br/>
        <input type="submit" value="get" onClick="goAjaxWithGet()"; />
        <input type="submit" value="post" onClick="goAjaxWithPost()"; />
   </form>
</body>
</html>


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP