Ajax原理及用原生js实现Ajax应用

什么是Ajax?

  • Asynchronous JavaScript and XML
  • 浏览器与服务器之间进行异步交互无需刷新页面的技术
Ajax原理
Ajax原理及用原生js实现Ajax应用
文章图片

1. 获取XMLHTTPRequest对象 HTML按钮









function getRequest() { var xmlHttp = null; try {// Chrome, Firefox, Opera, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { try {// Internet Explorer xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try {// Internet Explorer xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("your browser not support ajax!"); } } } return xmlHttp; }

通过js获取按钮对象,绑定按钮点击事件,获取XMLHTTPRequest对象
var request = getRequest(); window.onload = function(){ var btn01Ele = document.getElementById("btn01"); btn01Ele.onclick = function(){ alert(request); }; }

2. 发送GET请求 通过js获取按钮对象,绑定按钮点击事件,向后台AjaxRequestServlet发送请求参数
var btn02Ele = document.getElementById("btn02"); btn02Ele.onclick = function(){ //发送GET请求 //1.调用request对象的open()方法建立一个连接 //①method参数:请求方式 //②url参数:请求的目标地址 //发送请求参数:附着在URL地址后面 request.open("get", "AjaxRequestServlet?userName=Tom2015"); //2.调用request对象的send()方法发送请求数据 request.send(); };

【Ajax原理及用原生js实现Ajax应用】后台AjaxRequestServlet代码如下
public class AjaxRequestServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//获取浏览器端传入的请求参数 String userName = request.getParameter("userName"); System.out.println("userName="+userName); System.out.println("AjaxRequestServlet get..."); }

web.xml中配置AjaxRequestServlet的路径
AjaxRequestServlet AjaxRequestServlet com.atguigu.ajax.servlet.AjaxRequestServlet AjaxRequestServlet /AjaxRequestServlet

3. 发送POST请求 通过js获取按钮对象,绑定按钮点击事件,向后台AjaxRequestServlet发送请求参数
var btn03Ele = document.getElementById("btn03"); btn03Ele.onclick = function(){ //发送POST请求 //发送请求参数:将请求参数键值对以参数形式传递给send()方法 request.open("post", "AjaxRequestServlet"); //设置请求消息头为如下的值: //Content-Type:application/x-www-form-urlencoded request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); request.send("userName=Jerry2015&userPwd=123456"); };

后台AjaxRequestServlet中doPost方法的代码如下
public class AjaxRequestServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName = request.getParameter("userName"); System.out.println("userName="+userName); System.out.println("AjaxRequestServlet post..."); }}

接收响应的时机
Ajax原理及用原生js实现Ajax应用
文章图片

变量 解释
0 (未初始化) 对象已建立,但是尚未初始化(尚未调用open方法)
1 (初始化) 对象已建立,尚未调用send方法
2 (发送数据) send方法已调用,但是当前的状态及http头未知
3 (数据传送中) 已接收部分数据,因为响应及http头不全,这时通过resBodyponse和responseText获取部分数据会出现错误
4 (完成) 数据接收完毕,此时可以通过responseBody和responseText获取完整的回应数据
4. 接收文本格式的响应数据 通过js获取按钮对象,绑定按钮点击事件,向后台AjaxRequestText发送请求
var btn04Ele = document.getElementById("btn04"); btn04Ele.onclick = function(){ //接收【文本】格式的响应数据 request.open("post", "AjaxResponseText"); request.send(); //1.通过onreadystatechange事件监听readystate属性值的变化 request.onreadystatechange = function(){ //2.在readystat属性等于4并且status属性等于200时接收响应数据 if(request.readyState == 4 && request.status == 200) { var result = request.responseText; alert(result); } }; };

后台AjaxResponseText的doPost方法代码如下
public class AjaxResponseText extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//准备作为响应的文本数据 response.setContentType("text/html; charset=UTF-8"); PrintWriter writer = response.getWriter(); writer.write("佟刚老师英明神武,风流倜傥!"); } }

web.xml文件中,配置AjaxRequestText请求路径
AjaxResponseText AjaxResponseText com.atguigu.ajax.servlet.AjaxResponseText AjaxResponseText /AjaxResponseText

5. 接收XML格式的响应数据 通过js获取按钮对象,绑定按钮点击事件,向后台AjaxRequestXML发送请求
var btn05Ele = document.getElementById("btn05"); btn05Ele.onclick = function(){ //接收【XML】格式的响应数据 request.open("post", "AjaxResponseXML"); request.send(); //1.通过onreadystatechange事件监听readystate属性值的变化 request.onreadystatechange = function(){ //2.在readystat属性等于4并且status属性等于200时接收响应数据 if(request.readyState == 4 && request.status == 200) { //"Tom2015" //{user:{userName:Tom2015}} //使用responseXML属性接收XML格式的数据 var result = request.responseXML; //alert(result + " " + document); var userName = result.getElementsByTagName("userName")[0].firstChild.nodeValue; alert(userName); } }; };

后台AjaxResponseXML的doPost方法代码如下
public class AjaxResponseXML extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //准备XML数据,作为响应返回给浏览器 String xmlStr = "Tom2015"; //告诉浏览器,服务器端返回的数据是XML格式的 response.setContentType("text/xml; charset=UTF-8"); PrintWriter writer = response.getWriter(); writer.write(xmlStr); }}

web.xml文件中,配置AjaxRequestText请求路径
AjaxResponseXML AjaxResponseXML com.atguigu.ajax.servlet.AjaxResponseXML AjaxResponseXML /AjaxResponseXML

6. 接收JSON格式的响应数据
  1. 最外层只能是[]或{}
  2. []表示JSON数组:[value_1,value_2,…,value_n]
  3. {}表示JSON对象:{key_1:value_1,key_2:value_2,…,key_n:value_n}
  4. key数据类型:字符串
  5. value数据类型:
    基本数据类型:数值,字符串,布尔
    引用数据类型:数组和对象
  6. 优势:
    ①数据量小
    ②解析速度快
    ③是JavaScript中直接支持的数据格式,解析方便
通过js获取按钮对象,绑定按钮点击事件,向后台AjaxRequestJSON发送请求
var btn06Ele = document.getElementById("btn06"); btn06Ele.onclick = function(){ //接收【JSON】格式的响应数据 request.open("post", "AjaxResponseJSON"); request.send(); //1.通过onreadystatechange事件监听readystate属性值的变化 request.onreadystatechange = function(){ //2.在readystat属性等于4并且status属性等于200时接收响应数据 if(request.readyState == 4 && request.status == 200) { var result = request.responseText; //直接接收到的JSON数据是一个字符串类型,需要转换为JSON对象格式 result = eval("("+result+")"); //alert(typeof result); //"[\"Hello\",{userName:'Tom2015'}]" alert(result[1].userName); } }; };

后台AjaxResponseJSON的doPost方法代码如下
public class AjaxResponseJSON extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//准备JSON字符串 String jsonStr = "[\"Hello\",{userName:'Tom2015'}]"; response.setContentType("text/json; charset=UTF-8"); PrintWriter writer = response.getWriter(); writer.write(jsonStr); }}

web.xml文件中,配置AjaxRequestText请求路径
AjaxResponseJSON AjaxResponseJSON com.atguigu.ajax.servlet.AjaxResponseJSON AjaxResponseJSON /AjaxResponseJSON

    推荐阅读