Ajax底层原理及相关小案例

来源:互联网 发布:鹰朗el01正品淘宝店 编辑:程序博客网 时间:2024/04/20 14:14

Ajax的最大特点是:异步访问、局部刷新。核心是:XML。

Ajax的关键技术:

1.使用css搭建界面样式,负责页面的排版和美工

2.使用DOM进行动态显示和交互,对页面进行局部修改

3.使用XMLHttpRequest异步获取数据

4.使用JavaScript将所有的元素绑在一起

Ajax执行过程:

第一步:创建XMLHttpRequest对象

(注:不同的浏览器创建方式不同,可以提取为方法来进行调用)

function createXMLHttpRequest(){ if(window.ActiveOBject){   //IE浏览器    xhr =  new window.ActiveOBject("Microsoft.XMLHTTP"); }else{            //其他浏览器    xhr = new XMLHttpRequest(); }     }
第二步:建立到服务器的连接
//get方式  xhr.open("get", "http://localhost:8080/hdk/index.jsp?name="+name);  //post方式  xhr.open("post","http://localhost:8080/hdk/index.jsp?name="+name);  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");(上述连接方式是通过一个用户名的验证案例来写的,服务器的路径是验证信息跳转的jsp)
第三步:指定回调函数

(注:不同的Ajax响应回来后会自动调用函数,不同的Ajax请求步骤基本相同,但是差别和难易主要是在回调函数)function process(){  if(xhr.readyState == 4){     if(xhr.status == 200){     //200  404  500     //得到返回结果     var result = xhr.requestText;     //写到指定位置     document.getElementById("nametip");          }else{    alert("Ajax请求错误");}       }  }

在Ajax应用程序中,需要了解五种就绪状态,但通常只使用状态4。Http就绪状态,表示请求的状态或情形。
0(未初始化):请求没有发出(在调用open()之前)
1(初始化):请求已经建立但没发出(在调用send()之前)
2(发送数据):请求已经发出正在处理中(可以从响应得到数据的头部)
3(数据传送中):请求已经处理,响应中有部分数据可用,但是服务器还没完成响应
4(完成):响应已完成,可以访问服务器响应并使用它
状态码 status: 200,404,500

返回结果数据:requestText、responseXML

第四步:发送请求

//get方式xhr.send(null);//post方式xhr.send("name"+name);注:1.如果是get请求,参数已经附加在url中,采用send(null)即可。如果是post请求,需要通过send()来传递参数    2.如果是post请求,要在send之前添加如下语句来指定http header:xmlHttp.setRequestHeader("Content-Type“,"application/x-www-form-urlencoded");
其他:
XMLHttpRequest对象是Ajax应用的核心
1.属性
-readyState:提供当前HTML的就绪状态
-status:服务器响应的状态代码
-responseText/responseXML:服务器返回的请求响应文本/XML
2.方法
-open():建立到服务器的新请求
-send():向服务器发送请求
-setRequestHeader():设定请求头信息
3.事件
-onreadystatechange:用于指定回调函数

小案例:



user.jsp主要代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'user.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>  <script type="text/javascript">  var xhr;  function checkName(){  //获取用户名  var name = document.getElementById("name").value;    //判断用户名是否为空(JS)  if(name == ""){  document.getElementById("nametip").innerHTML="用户名不能为空";  return;  }  //判断用户名是否可用(ajax)  //1.创建XMLHttpRequest对象  createXMLHttpRequest();  //2.和服务器建立连接  //get方式  //xhr.open("get", "http://localhost:8080/hdk/index.jsp?name="+name);  //post方式  xhr.open("post","http://localhost:8080/hdk/index.jsp?name="+name);  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  //3.指定回调函数(ajax响应回来以后自动调用的函数)xhr.onreadystatechange=process;    //4.发送请求给服务器  //get方式  //xhr.send(null);  //post方式  xhr.send("name"+name);  }  //判断一般浏览器和ie浏览器的区别  function createXMLHttpRequest(){  if(window.ActiveXObject){//ie浏览器  xhr = new window.ActiveXObject("Microsoft.XMLHTTP");  }else{  xhr = new XMLHttpRequest();  }  }    function process(){  if(xhr.readyState == 4){  //缩短ajax请求的时间  if(xhr.status == 200){  //获取ajax的返回结果    var result = xhr.responseText;    //写到指定的位置    document.getElementById("nametip").innerHTML=result;    }else{  alert("ajax请求失败");  }  }  }  </script>  <body>  <form action=""  method="post"  >   姓名<input type="text" name="name" id="name"   onblur="checkName( )"><span id="nametip"></span>   <br>   密码<input type="text" name="pwd" id="pwd"><br>   密码<input type="text" name="repwd" id="repwd"><br>       <input type="submit" value="提交">   </form>    </body></html>
index.jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>    <%  //获取用户名  String name = request.getParameter("name");    //判断是否能用  boolean flag = false;  if(name.indexOf("sxt")>=0){  flag = true;  }    //给出客户端提示信息  if(flag){  out.print("用户名已经被占用");  }else{  out.print("用户名可以使用");  }  %>

 
原创粉丝点击