最近一段时间自己一直在学习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+"/";
%>
.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);
}
$(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
temp="
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);
}
});
});
根据邮政编码查询地址
处理请求的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
public ArrayList
return postlist;
}
public void setPostlist(ArrayList
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
System.out.println("HHAHA");
postlist=postservice.getPostListInfro(poststart);
return "SUCCESS";
}
}
配置文件:struts.xml
"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
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
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
}
DAOImpl层:PostDaoImpl.java
package com.ajax.daoimpl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
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
ArrayList
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`, `city`, `county`, `postalcode`) VALUES ('辽宁省', '沈阳市', '和平区', '110000');
INSERT INTO `post` (`province`, `city`, `county`, `postalcode`) VALUES ('辽宁省', '沈阳市', '大东区', '110000');
INSERT INTO `post` (`province`, `city`, `county`, `postalcode`) VALUES ('辽宁省', '沈阳市', '东陵区', '110000');
INSERT INTO `post` (`province`, `city`, `county`, `postalcode`) VALUES ('辽宁省', '沈阳市', '于洪区', '110000');
INSERT INTO `post` (`province`, `city`, `county`, `postalcode`) VALUES ('辽宁省', '沈阳市', '沈河区', '110000');
INSERT INTO `post` (`province`, `city`, `county`, `postalcode`) VALUES ('辽宁省', '沈阳市', '皇姑区', '110000');
INSERT INTO `post` (`province`, `city`, `county`, `postalcode`) VALUES ('辽宁省', '沈阳市', '沈北新区', '110000');
INSERT INTO `post` (`province`, `city`, `county`, `postalcode`) VALUES ('辽宁省', '沈阳市', '铁西区', '110020');
INSERT INTO `post` (`province`, `city`, `county`, `postalcode`) VALUES ('辽宁省', '沈阳市', '苏家屯区', '110100');
INSERT INTO `post` (`province`, `city`, `county`, `postalcode`) VALUES ('辽宁省', '沈阳市', '辽中县', '110200');
INSERT INTO `post` (`province`, `city`, `county`, `postalcode`) VALUES ('辽宁省', '沈阳市', '新民市', '110300');
INSERT INTO `post` (`province`, `city`, `county`, `postalcode`) VALUES ('辽宁省', '沈阳市', '法库县', '110400');
INSERT INTO `post` (`province`, `city`, `county`, `postalcode`) VALUES ('辽宁省', '沈阳市', '康平县', '110500');
INSERT INTO `post` (`province`, `city`, `county`, `postalcode`) VALUES ('辽宁省', '辽阳市', '辽阳市', '111000');
INSERT INTO `post` (`province`, `city`, `county`, `postalcode`) VALUES ('辽宁省', '辽阳市', '白塔区', '111000');
INSERT INTO `post` (`province`, `city`, `county`, `postalcode`) VALUES ('辽宁省', '辽阳市', '宏伟区', '111000');