1.为何要使用Ajaxjavascript
优势: 局部刷新 提升用户体验html
2.Ajax发出请求的demo前端
这里使用servlet 到后台java
2.1使用到的技术jquery
(1)jqueryajax
(2)Ajax服务器
(3)servletjsp
(4) 输出流 PrintWriter out = response.getWriter()ui
2.2 实现过程spa
2.2.1 前端
新建jsp页面
编写一个页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="./js/jquery-1.8.3.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ajax入门案例</title>
<script>
$(function(){
//光标离开事件
$("#userName").blur(function(){
var userName = $("#userName").val();
//建立XmlHttpRequest对象
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//建立链接
xmlhttp.open("GET","${pageContext.request.contextPath }/ajaxTest?userName="+userName);
//发送请求
xmlhttp.send();
//使用事件获得响应数据,并处理结果
xmlhttp.onreadystatechange=function(){
//xmlhttp.readyState==4 表示客户端请求一切正常
//xmlhttp.status==200 表示服务器端响应一切正常
//alert(xmlhttp.readyState);
//alert(xmlhttp.status);
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//document.getElementById("Prompt").innerHTML=xmlhttp.responseText;//得到服务器响应正文
$("#Prompt").html(xmlhttp.responseText);//得到服务器响应正文
}
}
})
});
</script>
</head>
<body>
<!--http://localhost:8080/day22_ajax_01/regist.jsp -->
用户名:<input type="text" name="userName" id="userName"><span id="Prompt"></span><br />
用户名2:<input type="text" name="password" id="password" placeholder="比较框"><br />
</body>
</html>
2.2.2 后台
package cn.ma.ajax;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 光标离开 发出Ajax请求
* http://localhost:8080/day22_ajax_01/regist.jsp
*/
public class AjaxTest extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName");
PrintWriter out = response.getWriter();
if("张三".equals(userName)){
out.write("该帐号已被注册");
}else{
out.write("该帐号可用");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
3. 效果