Ajax的初级使用

、AJAX简介(本文的例子都使用的是原生的ajax)
  老技术新用法
、异步和同步区别
、XMLHttpRequest对象(面试题)
属性:
  readyState:  

    0:未初始化

    1:open方法已经调用了

    2:send方法已经调用了

    3:接收到了响应消息头,但没有接收到正文

    4:接收到了响应正文。响应结束

  responseText:只读的。返回的是String

    作用:接收服务器返回的文本类型的正文数据。

  responseXML:只读的。返回的是Document对象(JS中文档模型)

    作用:接收服务器返回的XML类型的正文数据。

  status:只读的。返回的是short

    作用:接收服务器返回的响应状态码

  statusText:只读的。返回的是String

    作用:接收服务器返回的响应吗描述

方法:

l open(String method,String url,boolean async):建立与服务器的链接。

  method:请求方式。GET|POST

  url:请求的服务器地址。

  async:是否是异步。true是异步的。默认就是true。

l send(String data):发出请求。data参数是请求正文的内容数据。

l setRequestHeader(String headerName,String headerValue):设置请求消息头。

l getAllResponseHeaders():返回所有的响应消息头。是一个String字符串。

l getResponseHeader(headerName):返回指定头的值。是一个String字符串。

事件处理器:onreadystatechange:执向一个函数。XMLHttpRequest对象的readyState的每次变化都会触发onreadystatechange指向的事件处理器。

、GET和POST请求的发送
、服务器端返回的数据类型:
  XML: 返回的是xml对象
  JSON:返回的是文本类型,需要转换

编码步骤:

 function getXHR() {
var xmlHttp; try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) { // Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) { try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("您的浏览器不支持AJAX!");
return false;
}
}
}
return xmlHttp;
}

util.js

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>AJAX的编码步骤:测试异步交互是可行的</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="${pageContext.request.contextPath}/util.js"></script>
<script type="text/javascript">
window.onload=function(){
//window.onload是一个事件,当文档加载完成之后触发该事件
document.getElementById("bt1").onclick=function(){
//发出异步请求:步骤 //1、得到xhr(XMLHttpRequest)对象
var xhr = getXHR();
//2、注册状态变化监听器
xhr.onreadystatechange=function(){
//做出具体的处理
if(xhr.readyState==4){//接收到了响应正文。响应结束
if(xhr.status==200){//200:服务器成功返回页面
alert("服务器已经响应结束了,去看看吧");
}
}
}
//3、建立与服务器的链接
//如果访问的地址相同,浏览器就不会真正的发出请求 ?time="+new Date().getTime()
xhr.open("GET","${pageContext.request.contextPath}/servlet/ServletDemo1?time=");
//4、向服务器发出请求
xhr.send(null);//没有正文
}
}
</script>
</head> <body>
<input id="bt1" type="button" value="点我呀"/>
<%--
不论type是什么类型,只要单击鼠标就会执行,window.load=function事件
--%>
</body>
</html>

一个验证用户名是否存在例子:(理解POST和GET提交时send方法传值的区别)

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>检测用户名是否可用</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<script type="text/javascript" src="${pageContext.request.contextPath}/util.js"></script>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
window.onload=function(){
document.getElementById("username").onblur=function(){//失去焦点
if(this.value==""){
alert("请输入用户名");
this.focus();//恢复焦点
return;
}
//发出异步请求
var xhr = getXHR();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){ document.getElementById("msg").innerHTML=xhr.responseText;
//responseText接收服务器返回的文本类型的正文数据。
//放到名为msg的span(属于一个行内元素)中
}
}
}
/*GET提交时,在send中传值是不起作用的;
xhr.open("GET","${pageContext.request.contextPath}/servlet/ServletDemo2?username="+this.value+"&time="+new Date().getTime());
xhr.send(null);
*/ //
xhr.open("POST","${pageContext.request.contextPath}/servlet/ServletDemo2?time="+new Date().getTime());
//设置请求消息头:告知客户端提交的正文的MIME类型
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("username="+this.value);
}
}
</script>
</head> <body>
<form action="" method="post">
用户名:<input type="text" id="username" name="username"/><span id="msg"></span><br/>
密码:<input type="password" id="password" name="password"/><br/>
<input type="submit" value="注册"/>
</form>
</body>
</html>

页面

 package com.itheima.servlet;

 import java.io.IOException;

 import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class ServletDemo2 extends HttpServlet {
private String usernames[] = {"admin","wzhting"};//预先存在的用户名,也可连接数据库取;此处只是为了说明ajax做了简化处理 public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
boolean b = false;//是否可用
for(String s:usernames){
if(s.equals(username)){
b = true;
break;
}
} response.setContentType("text/html;charset=UTF-8");
if(b){
response.getWriter().write("<font color='red'>用户名不可用</font>");
}else{
response.getWriter().write("<font color='green'>用户可用</font>");
} } public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }

ServletDemo2

一个理解(利用jsp页面返回数据)例子:

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>显示所有的商品</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<script type="text/javascript" src="${pageContext.request.contextPath}/util.js"></script>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style type="text/css">
.odd{
background-color: #c3f3c3;
}
.even{
background-color: #f3c3f3;
}
</style>
<script type="text/javascript">
var flag = false;
window.onload=function(){
document.getElementById("bt1").onclick=function(){
//发出异步请求
var xhr = getXHR();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
if (flag == false) {
document.getElementById("d1").innerHTML=xhr.responseText;// 文本类型 text/*
flag = true;
} else {
document.getElementById("d1").innerHTML="";
flag = false;
}
}
}
}
xhr.open("GET","${pageContext.request.contextPath}/servlet/ServletDemo3?time="+new Date().getTime());
xhr.send(null);
}
}
</script>
</head> <body>
<input type="button" id="bt1" value="显示商品"/>
<hr/>
<div id="d1"></div>
</body>
</html>

主页面

 package com.itheima.servlet;

 import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.itheima.domain.Product; public class ServletDemo3 extends HttpServlet {
private List<Product> products = new ArrayList<Product>();
public void init() throws ServletException {
products.add(new Product(1, "充气筒", 20));
products.add(new Product(2, "三国杀", 10));
products.add(new Product(3, "扑克", 10));
products.add(new Product(4, "洗衣粉", 10));
products.add(new Product(5, "肥皂", 7));
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("products", products);
request.getRequestDispatcher("/listProducts.jsp").forward(request, response);
//jsp页面因为是先编译成servlet在运行的,而servlet中的jsp页面就变成了如下形式的代码
//out.write("<html>\r\n");
//所以response的是整个jsp页面
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }

ServletDemo3

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>title</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body>
<table border="1" width="438">
<tr>
<th>编号</th><%-- th比表示标题的一格,会自动加黑加粗 --%>
<th>名称</th>
<th>单价</th>
</tr>
<c:forEach items="${products}" var="p" varStatus="vs">
<tr class="${vs.index%2==0?'odd':'even' }">
<td>${p.id}</td>
<td>${p.name}</td>
<td>${p.price}</td>
</tr>
</c:forEach>
</table>
</body>
</html>

返回数据的jsp页面

结果表明:jsp页面因为是先编译成servlet再运行的,故jsp页面会变成了如下形式的代码:

    out.write("<html>\r\n");
out.write("\t<head>\r\n");
out.write("\t\t<title>title</title>\r\n");
out.write("\t</head>\r\n");
out.write("\t<bodystyle=\"background-color:lightblue\">\r\n");
out.write("\r\n");
   ……

//所以jsp页面可以返还给xhr.responseText;即使servlet中没有response.getWriter().write("……");

 
 
 
 
 
 
 
 
 
上一篇:Java从零开始学七(选择结构)


下一篇:restful处理