当前位置: 代码迷 >> Ajax >> AJAX在线基础(待续2)
  详细解决方案

AJAX在线基础(待续2)

热度:158   发布时间:2012-10-06 17:34:01.0
AJAX在线基础(待续二)
例子一:用户检测,在输入用户名称的时候响应AJAX,检查是否存在用户,然后渲染页面
checkUser.jsp如下:页面的输入框值改变响应请求检验用户
<%@ page language="java" pageEncoding="utf-8"%>
<html>
<head>
<script type="text/javascript">
var xmlhttp;
         function checkUser() {
           clear();
            var user = document.getElementById("id").value;
            xmlhttp = createXML();
            xmlhttp.onreadystatechange = function(){
            if (xmlhttp.readyState == 4) {//readystate 为4即数据传输结束
    if(xmlhttp.status == 200){
setResult(xmlhttp.responseText);
  
}
   }
            }
            var url = "checkUser?username=" + user;
            xmlhttp.open("GET", url, true);
            xmlhttp.send(null);
         }
        
         function clear() {
            document.getElementById("result").innerHTML = "";
         }
        
        function createXML() {
            var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
        return xmlhttp;
         }
        
         function setResult(result) {
           var res = document.getElementById("result");
           if(result == 'true') {
              res.innerHTML = "<font color='black'>恭喜你该用户可以使用</font>";
           }else {
             res.innerHTML = "<font color='red'>对不起该用户已经存在</font>";
           }
         }
        
        
     </script>
</head>
<body>
<input type="text" id="id" onchange="checkUser();"/><span id="result"></span>
</body>
</html>
checkUser.java代码如下:
package com.moom;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class checkUser extends HttpServlet {
private static List<String> users = new ArrayList<String>();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
if(users.contains(username)) {
out.print("false");
}else {
out.print("true");
}
out.flush();
out.close();
}
public void init(ServletConfig arg0) throws ServletException {
users.add("100");
users.add("101");
users.add("102");
super.init(arg0);
}
}
例子二:动态加载查询用户,根据下拉列表选择的年份获取当年注册的用户
Userlist.jsp代码如下:
<%@ page language="java" pageEncoding="utf-8"%>
<html>
<head>
<script type="text/javascript">
var xmlhttp;
         function getUsers() {
          //每次在获取前先清除原有的数据
           clear();
            var year = document.getElementById("year").value;
            xmlhttp = createXML();
            xmlhttp.onreadystatechange = function(){
            if (xmlhttp.readyState == 4) {//readystate 为4即数据传输结束
    if(xmlhttp.status == 200){
setUsers(); //把获取到的用户设置到option中
}
   }
            }
            var url = "getUsers?year=" + year;
            xmlhttp.open("GET", url, true);
            xmlhttp.send(null);
         }
        
         function clear() {
            var users = document.getElementById("user");
           //循环删除数据
while(users.childNodes.length) {
                users.removeChild(users.childNodes[0]);
            }
         }
        function createXML() {
            var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
        return xmlhttp;
         }
         function setUsers() {
           //先添加一个Option子节点,在给option添加一个文本子节点
           var users = xmlhttp.responseXML.getElementsByTagName("user");
           var us = document.getElementById("user");
           for(var i=0; i<users.length; i++) {
              var u = document.createElement("<option>");
              var text = document.createTextNode(users[i].firstChild.data);
              u.appendChild(text);
              us.appendChild(u);
           }
         }
     </script>
</head>
<body>
<select id="year" name="year" onchange="getUsers();">
   <option value="">请选择年份</option>
   <option value="2005">2005</option>
   <option value="2006">2006</option>
   <option value="2007">2007</option>
   <option value="2008">2008</option>
</select>
<select id="user" name="user">
   <option value="">请选择人员</option>
</select>
</body>
</html>
服务器端的JAVA代码如下:
package com.moom;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class getUsers extends HttpServlet {
private static List<String> years = new ArrayList<String>();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/xml");
response.setCharacterEncoding("utf-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
String year = request.getParameter("year");
out.print("<?xml version='1.0' encoding='UTF-8'?>");
out.print("<users>");
if(!years.contains(year)) {
out.print("<user>没有用户</user>");
}else {
if(year.equals("2005")) {
out.print("<user>张三</user>");
out.print("<user>李四</user>");
out.print("<user>王五</user>");
}else if(year.equals("2006")) {
out.print("<user>李好</user>");
out.print("<user>成周</user>");
out.print("<user>吴浩</user>");
}else if(year.equals("2007")) {
out.print("<user>生成</user>");
out.print("<user>雨果</user>");
out.print("<user>美如</user>");
}else if(year.equals("2008")) {
out.print("<user>张洁</user>");
out.print("<user>乘风</user>");
out.print("<user>可是</user>");
}
}
out.print("</users>");

out.flush();
out.close();
}
public void init(ServletConfig arg0) throws ServletException {
years.add("2005");
years.add("2006");
years.add("2007");
years.add("2008");
super.init(arg0);
}
}
例子三:动态刷新数据,在实际的应用中,很多时候页面只是一部分需要定时的刷新,在以前都是通过手动刷新的方式来刷新页面,显然不是很合理,速度也不是很快,有了AJAX,只需要对需要刷新的地方做一个定时器,每到时间就调用一次刷新函数,获取最新数据,在利用DOM把获取到的最新数据反映到HTML页面当中去。
JS中利用setTimeOut(“method”,time):来设置定时任务,只要设置要在给定的time时间下,就会调用method函数,Method函数等于就相当于发出响应,获取服务器最新数据,拿到数据利用DOM对象渲染页面。
例子四:进度条的制作
主要也是通过定时的发送请求给服务器,然后服务器返回任务完成比例的百分比,客户端通过JS和DOM再去渲染页面,表示结果,进度条的显示主要也是通过百分比去控制页面元素的颜色显示来动态的感觉到进度的变化。
例子五:调用WEB服务,利用AJAX可以去调用别的系统中的WEB服务,返回结果进行解析。
例子六:动态表单填写,在购物的时候,用户的购物信息一般是确定的,可以在用户填上用户名之后,就用AJAX调用后台查询出用户详细信息,利用JS DOM渲染 页面,把用户的详细信息填入相应的表单。
  相关解决方案