关于Ajax的概念不再做解释了,我想通过三个小例子来让大家对Ajax有个清晰的认识。要学习它,必须从最基础最原始的方式开始认识,然后通过使用框架来提升效率,逐步认识它。
一.原生js版(注册的用户名是否重复的校验)
前端js代码:
<script type="text/javascript">
var xmlHttpRequest;
function createXmlHttpRequest(){
if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
}
function request(){
var uname = document.getElementById("username").value;
if(uname==""){//用户名为空则不作判断是否存在
return;
}
//请求字符串
var url = " CheckUserServlet";
//1创建XMLHttpRequest组件
xmlHttpRequest = createXmlHttpRequest();
//2设置回调函数
xmlHttpRequest.onreadystatechange = handle;
//3初始化XMLHttpRequest组件
xmlHttpRequest.open("POST",url,true);
//4.设置请求头(post类型需要)
xmlHttpRequest.send(null);
xmlHttpReq.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
//5.发送请求
xmlHttpReq.send("username=" + uname);
}
function handle(){
if(xmlHttpRequest.readyState==4
&&xmlHttpRequest.status==200 ){
var b = xmlHttpRequest.responseText;
//alert(b);
if(b=="true"){
document.getElementById("result").innerHTML="用户名已存在";
}else{
document.getElementById("result").innerHTML="用户名可以使用";
}
}
}
</script>
后台servlet查找用户表
public class CheckUserServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponseresponse)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wp","root","root");
PreparedStatement ps = con.prepareStatement("select * from user where u_name='"+username+"'");
ResultSet rs = ps.executeQuery();
if(rs.next()){
out.println("true");
}else{
out.println("false");
}
con.close();
out.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
二.JQuery框架版(一个搜索框的自动补全)
前端js代码(使用了jQuery框架,封装了对Ajax的操作,是不是简单了许多)
<scripttype="text/javascript">
$(document).ready(function() {
$('#query').keyup(function() {
reg=/^[a-z|A-Z|0-9]/;//以字母或者数字开头的不予响应
if(reg.test($('#query').val()))return;
$.ajax({
url: 'AutoServlet?body='+$('#query')[0].value,
type: 'GET',
dataType: 'json', //以json形式返回
timeout: 2000,
cache: false,
error: erryFunction, //错误执行方法
success: succFunction //成功执行方法
})
function erryFunction() {
alert("error");
}
function succFunction(data) {
$.each(data, function (index, value) { //遍历
$("#auto").append("<br>"+value);
});
}
});
});
</script>
后台可以使用Servlet处理,将得到的结果使用Gson转换为json形式返回给客户端:
public class AutoServlet extendsHttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
List<String> names = new ArrayList<String>();
String body = request.getParameter("body");
body = new String(body.getBytes("ISO-8859-1"),"UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriterout = response.getWriter();
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/wp","root","root");
PreparedStatement ps = con.prepareStatement("select distinct (name) from book where namelike '%"+body+"%'");
ResultSet rs = ps.executeQuery();
while(rs.next()){
names.add(rs.getString("name"));
}
con.close();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
//使用谷歌的gson转换成json
Gson gson = new Gson();
String jsonString = gson.toJson(names);
out.println(jsonString);
out.close();
}
}
三.快捷式DWR版(省市二级联动)
前端js和html代码
<html>
<head>
<meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
<title>Insert titlehere</title>
<script type='text/javascript'src='/TestDWR/dwr/interface/MyDemo.js'></script>
<script type='text/javascript'src='/TestDWR/dwr/engine.js'></script>
<script type='text/javascript'src='/TestDWR/dwr/util.js'></script>
<script type="text/javascript">
function change(pro){
MyDemo.findCity(pro,callback);
}
function callback(data){
DWRUtil.removeAllOptions("city");
DWRUtil.addOptions("city",data,"id","name");
}
</script>
</head>
<body>
<select id="pro"οnchange="change(this.value)">
<option value="1">湖北省</option>
<option value="2">湖南省</option>
<option value="3">山东省</option>
</select>
<select id="city"></select>
</body>
</html>
服务器端Java代码:
public class Demo1 {
List<City> citys1 = new ArrayList<City>();
List<City> citys2 = new ArrayList<City>();
List<City> citys3 = new ArrayList<City>();
Map<Integer,List<City>> cityMap = new HashMap<Integer, List<City>>();
public Demo1(){
citys1.add(new City(100,"武汉市"));
citys1.add(new City(101,"宜昌市"));
citys1.add(new City(102,"仙桃市"));
citys1.add(new City(103,"黄冈市"));
citys2.add(new City(200,"长沙市"));
citys2.add(new City(201,"株洲市"));
citys2.add(new City(202,"岳阳市"));
citys2.add(new City(203,"湘潭市"));
citys3.add(new City(300,"烟台市"));
citys3.add(new City(301,"青岛市"));
citys3.add(new City(302,"秦皇岛市"));
cityMap.put(1,citys1);
cityMap.put(2,citys2);
cityMap.put(3,citys3);
}
public List<City> findCity(int id ){
if(cityMap.containsKey(id)){
returncityMap.get(id);
}
return null;
}
}
后台的代码就是如此,servlet不需要了,返回的结果也不需要转换了,看起来就像在客户端直接调用服务器端java代码一样.
但是多了些配置和引用:
1. web.xml的配置
2. dwr.xml的配置
3. 自动生成的js脚本的引用(需要先注入)
我们会发现,所谓的框架,不过是封装了一些繁杂无味的机械化操作,将这些平时会重复使用的部分写好,把变化的部分提炼出来,以配置的形式让人修改,达到的效果是相同的,但开发的效率却大大提高。就像所有的Ajax框架和组件一样,底层的操作少不了,你不需要做,但你得知道有这么一出,这就是基本原理。