最近一段时间自己一直在学习AJAX,忽然顿悟ajax的强大功能,实在让人吃惊。在接下来的几篇博客里,我将分享在学习过程中,自己写的一些小例子,欢迎大家一起交流学习。。。欢迎各位拍砖。。你的关注是我不断前进的动力。话不多说,直接上例子程序。(完全的源码地址:http://down.51cto.com/data/1569671)
首选,说说本例子的功能。(如下几幅图)
主页面:indexPostalCode.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 'indexPostalCode.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">
<script src="js/jquery-1.8.2.min.js"></script>
<style>
.top {
width:300px;
margin-left:35%;
border: solid 1px red;
height:300px;
}
#city,#county{
margin-left: 66px;
}
#postalcode,#province,#city,#county,#but{
margin-top: 20px;
}
#but{
margin-left:44%;
width:60px;
}
#title{
display:none;
color: red;
}
#titlediv{
height:20px;
}
#resultlist{
background-color: rgb(237,235,241);;
width: 153px;
min-height:20px;
margin-top: -180px;
margin-left: 604px;
position: absolute;
display:none;
}
#resultlist>li{
margin-top:5px;
}
.currentstatus{
background:rgb(110,248,127);
}
</style>
<script>
$(document).ready(function(){
var postalcode=$("#postalcode");
var province=$("#province");
var city=$("#city");
var county=$("#county");
var but=$("#but");
var title=$("#title");
var xmlHttp; //用于保存XMLHttpRequest对象的全局变量
//用于创建XMLHttpRequest对象
function createXmlHttp() {
//根据window.XMLHttpRequest对象是否存在使用不同的创建方式
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest(); //FireFox、Opera等浏览器支持的创建方式
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//IE浏览器支持的创建方式
}
}
function loadFAQCallback() {
if (xmlHttp.readyState == 4&&xmlHttp.status==200) {
var data = JSON.parse(xmlHttp.responseText).post;
if(typeof data.postalcode=="string"){
province.val(data.province);
city.val(data.city);
county.val(data.county);
}else{
title.css("display","block")
title.html("该邮政编号有误,请重新输入!");
title.hide(2000);
}
}
}
function loadFAQCallbackKeyUp() {
if (xmlHttp.readyState == 4&&xmlHttp.status==200) {
var data = JSON.parse(xmlHttp.responseText).postlist;
showPostList(data);
$("#resultlist li").mouSEOver(function(){
$(this).addClass("currentstatus");
});
$("#resultlist li").mouSEOut(function(){
$(this).removeClass("currentstatus");
});
$("#resultlist li").click(function(){
$("#postalcode").val($(this).text());
$("#resultlist").css("display","none");
});
}
}
//展示匹配列表
function showPostList(data){
$("#resultlist").css("display","block");
var len=data.length;
var liList=new Array();
var temp="";
for(i=0;i<len;i++){
temp="<li>"+data[i].postalcode+"</li>";
liList.push(temp);
}
//var list=liList.join();
//alllist==list.replace(/,/g,'');
var alllist=liList.join("");//拼接html
$("#resultlist").html(alllist);
}
//判断键盘输入是否为数字
postalcode.keypress(function(){
if(event.keyCode==13){
debugger;
$("#resultlist").css("display","none");
}else if(event.keyCode<48||event.keyCode>57){
return false;
}
});
//键盘输入一个字符时,ajax发一次请求
postalcode.keyup(function(){
if(event.keyCode>47||event.keyCode<58){
var postvalue=postalcode.val();
createXmlHttp(); //创建XmlHttpRequest对象
xmlHttp.onreadystatechange = loadFAQCallbackKeyUp;
xmlHttp.open("GET","getPostList.action?poststart="+postvalue,true);
xmlHttp.send(null);
}
});
but.click(function(){
var postalcode=$("#postalcode").val();
if(postalcode.length==0){
title.css("display","block")
title.html("输入不能为空");
title.hide(2000);
}else if (postalcode.length<6){
title.css("display","block")
title.html("请输入6位邮政编码");
title.hide(2000);
}else{
createXmlHttp(); //创建XmlHttpRequest对象
xmlHttp.onreadystatechange = loadFAQCallback;
xmlHttp.open("GET","getPost.action?post.postalcode="+postalcode,true);
xmlHttp.send(null);
}
});
});
</script>
</head>
<body>
<div class="top">
<center> <h3>根据邮政编码查询地址</h3></center>
<div id="titlediv"><span id="title"></span></div>
<div> <label>请输入邮政编码:</label><input type="text" id="postalcode" maxlength="6"></input></div>
<div><label>省自治区直辖市:</label><input type="text" id="province"></input></div>
<div><label>地级市:</label><input type="text" id="city"></input></div>
<div><label>县市区:</label><input type="text" id="county"></input></div>
<input type="button" id="but" value="查询"/>
</div>
<div id="resultlist">查询结果</div>
</body>
</html>
处理请求的Action:PostAction.java
package com.ajax.action;
import java.util.ArrayList;
import com.ajax.model.Post;
import com.ajax.service.PostService;
import com.opensymphony.xwork2.ActionSupport;
public class PostAction extends ActionSupport{
Post post;
public String poststart;
ArrayList<Post> postlist ;
public ArrayList<Post> getPostlist() {
return postlist;
}
public void setPostlist(ArrayList<Post> postlist) {
this.postlist = postlist;
}
public String getPoststart() {
return poststart;
}
public void setPoststart(String poststart) {
this.poststart = poststart;
}
PostService postservice=new PostService();
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post = post;
}
public String showPostInfro(){
System.out.println("hheh");
String postcodes=post.getPostalcode();
post= postservice.getPostInfro(postcodes);
return "SUCCESS";
}
public String showPostListInfro(){
postlist=new ArrayList<Post>();
System.out.println("HHAHA");
postlist=postservice.getPostListInfro(poststart);
return "SUCCESS";
}
}
配置文件:struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.custom.i18n.resources" value="faq"></constant>
<constant name="struts.i18n.encoding" value="UTF-8"></constant>
<package name="post" extends="json-default">
<action name="getPost" class="com.ajax.action.PostAction" method="showPostInfro">
<result name="SUCCESS" type="json">
</result>
</action>
<action name="getPostList" class="com.ajax.action.PostAction" method="showPostListInfro">
<result name="SUCCESS" type="json">
</result>
</action>
</package>
</struts>
Model层:Post.java
package com.ajax.model;
public class Post {
public String postalcode;
public String province;
public String city;
public String county;
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
public String getPostalcode() {
return postalcode;
}
public void setPostalcode(String postalcode) {
this.postalcode = postalcode;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Service层:PostService.java
package com.ajax.service;
import java.util.ArrayList;
import com.ajax.dao.PostDao;
import com.ajax.daoimpl.PostDaoImpl;
import com.ajax.model.Post;
public class PostService {
PostDao postdao=new PostDaoImpl();
public Post getPostInfro(String postalcode){
return postdao.getPostInfro(postalcode);
}
public ArrayList<Post> getPostListInfro(String poststart) {
return postdao.getPostListInfro(poststart);
}
}
DAO层:PostDao.java
package com.ajax.dao;
import java.util.ArrayList;
import com.ajax.model.Post;
public interface PostDao {
public Post getPostInfro(String postalcode);
public ArrayList<Post> getPostListInfro(String poststart);
}
DAOImpl层:PostDaoImpl.java
package com.ajax.daoimpl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import com.ajax.dao.PostDao;
import com.ajax.model.Post;
import com.ajax.util.DB;
public class PostDaoImpl implements PostDao {
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
/*
* 获取邮政编码对应的地址信息
* @see com.ajax.dao.PostDao#getpost()
*/
public Post getPostInfro(String postalcode) {
Post post =new Post();
String sql="select distinct * from post where postalcode='"+postalcode+"'";
conn=DB.getConn();
stmt=DB.getStatement(conn);
rs=DB.getResultSet(stmt,sql);
try {
while(rs.next()){
post.setProvince(rs.getString("province"));
post.setCity(rs.getString("city"));
post.setCounty(rs.getString("county"));
post.setPostalcode(rs.getString("postalcode"));
}
} catch (sqlException e) {
e.printStackTrace();
}
System.out.println(post.getProvince());
return post;
}
/*
* 获取postlist列表
* @see com.ajax.dao.PostDao#getPostList(java.lang.String)
*/
public ArrayList<Post> getPostListInfro(String poststart) {
ArrayList<Post> postlist=new ArrayList<Post>();
String sql="select * from (select * from post group by postalcode) as postdetail where postalcode like '"+poststart+"%' limit 0,10";
System.out.println(sql);
conn=DB.getConn();
stmt=DB.getStatement(conn);
rs=DB.getResultSet(stmt,sql);
try {
while(rs.next()){
Post p=new Post();
p.setPostalcode(rs.getString("postalcode"));
p.setProvince(rs.getString("province"));
p.setCity(rs.getString("city"));
p.setCounty(rs.getString("county"));
postlist.add(p);
}
} catch (sqlException e) {
e.printStackTrace();
}
System.out.println(postlist.size());
return postlist;
}
}
自己封装数据库连接工具类:DB.JAVA
package com.ajax.util;
import java.sql.*;
public class DB {
public static Connection getConn() {
Connection conn = null;
try {
Class.forName("com.MysqL.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:MysqL://localhost/demo?user=root&password=root");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (sqlException e) {
e.printStackTrace();
}
return conn;
}
public static PreparedStatement prepare(Connection conn,String sql) {
PreparedStatement pstmt = null;
try {
if(conn != null) {
pstmt = conn.prepareStatement(sql);
}
} catch (sqlException e) {
e.printStackTrace();
}
return pstmt;
}
public static PreparedStatement prepare(Connection conn,String sql,int autoGenereatedKeys) {
PreparedStatement pstmt = null;
try {
if(conn != null) {
pstmt = conn.prepareStatement(sql,autoGenereatedKeys);
}
} catch (sqlException e) {
e.printStackTrace();
}
return pstmt;
}
public static Statement getStatement(Connection conn) {
Statement stmt = null;
try {
if(conn != null) {
stmt = conn.createStatement();
}
} catch (sqlException e) {
e.printStackTrace();
}
return stmt;
}
public static ResultSet getResultSet(Statement stmt,String sql) {
ResultSet rs = null;
try {
if(stmt != null) {
rs = stmt.executeQuery(sql);
}
} catch (sqlException e) {
e.printStackTrace();
}
return rs;
}
public static void executeUpdate(Statement stmt,String sql) {
try {
if(stmt != null) {
stmt.executeUpdate(sql);
}
} catch (sqlException e) {
e.printStackTrace();
}
}
public static void close(Connection conn) {
try {
if(conn != null) {
conn.close();
conn = null;
}
} catch (sqlException e) {
e.printStackTrace();
}
}
public static void close(Statement stmt) {
try {
if(stmt != null) {
stmt.close();
stmt = null;
}
} catch (sqlException e) {
e.printStackTrace();
}
}
public static void close(ResultSet rs) {
try {
if(rs != null) {
rs.close();
rs = null;
}
} catch (sqlException e) {
e.printStackTrace();
}
}
}
数据库:数据表名:post
简单列举几条数据,具体全国邮政编码相关数据网上去搜吧。
INSERT INTO `post` (`province`,`city`,`county`,`postalcode`) VALUES ('辽宁省','沈阳市','110000');
INSERT INTO `post` (`province`,'和平区','大东区','东陵区','于洪区','沈河区','皇姑区','沈北新区','铁西区','110020');
INSERT INTO `post` (`province`,'苏家屯区','110100');
INSERT INTO `post` (`province`,'辽中县','110200');
INSERT INTO `post` (`province`,'新民市','110300');
INSERT INTO `post` (`province`,'法库县','110400');
INSERT INTO `post` (`province`,'康平县','110500');
INSERT INTO `post` (`province`,'辽阳市','111000');
INSERT INTO `post` (`province`,'白塔区','宏伟区','111000');