AJAX实例--根据邮政编号动态获取省,市,县三级地区+仿百度搜索下拉提示

最近一段时间自己一直在学习AJAX,忽然顿悟ajax的强大功能,实在让人吃惊。在接下来的几篇博客里,我将分享在学习过程中,自己写的一些小例子,欢迎大家一起交流学习。。。欢迎各位拍砖。。你的关注是我不断前进的动力。话不多说,直接上例子程序。(完全的源码地址:http://down.51cto.com/data/1569671)

首选,说说本例子的功能。(如下几幅图)

  1. 输入邮政编码,点击查询获取数据填充三个文本框;

  2. 仿百度模糊查询下拉提示

wKioL1PNJUfD6_DGAAChJ1KNbTM679.jpg

wKiom1PNJC-hheroAADCy6QWnXs349.jpg

wKiom1PNJDTAY8wLAADolzR2alU136.jpg

页面indexPostalCode.jsp

@H_404_27@<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

@H_404_27@<%

@H_404_27@String path = request.getContextPath();

@H_404_27@String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

@H_404_27@%>

@H_404_27@<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

@H_404_27@<html>

@H_404_27@ <head>

@H_404_27@ <base href="<%=basePath%>">

@H_404_27@ <title>My JSP 'indexPostalCode.jsp' starting page</title>

@H_404_27@ <Meta http-equiv="pragma" content="no-cache">

@H_404_27@ <Meta http-equiv="cache-control" content="no-cache">

@H_404_27@ <Meta http-equiv="expires" content="0">

@H_404_27@ <Meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

@H_404_27@ <Meta http-equiv="description" content="This is my page">

@H_404_27@ <script src="js/jquery-1.8.2.min.js"></script>

@H_404_27@<style>

@H_404_27@.top {

@H_404_27@ width:300px;

@H_404_27@ margin-left:35%;

@H_404_27@ border: solid 1px red;

@H_404_27@ height:300px;

@H_404_27@}

@H_404_27@#city,#county{

@H_404_27@ margin-left: 66px;

@H_404_27@}

@H_404_27@#postalcode,#province,#city,#county,#but{

@H_404_27@ margin-top: 20px;

@H_404_27@}

@H_404_27@#but{

@H_404_27@margin-left:44%;

@H_404_27@width:60px;

@H_404_27@}

@H_404_27@#title{

@H_404_27@display:none;

@H_404_27@color: red;

@H_404_27@}

@H_404_27@#titlediv{

@H_404_27@height:20px;

@H_404_27@}

@H_404_27@#resultlist{

@H_404_27@background-color: rgb(237,235,241);;

@H_404_27@width: 153px;

@H_404_27@min-height:20px;

@H_404_27@margin-top: -180px;

@H_404_27@margin-left: 604px;

@H_404_27@position: absolute;

@H_404_27@display:none;

@H_404_27@}

@H_404_27@#resultlist>li{

@H_404_27@margin-top:5px;

@H_404_27@}

@H_404_27@.currentstatus{

@H_404_27@background:rgb(110,248,127);

@H_404_27@}

@H_404_27@</style>

@H_404_27@<script>

@H_404_27@$(document).ready(function(){

@H_404_27@ var postalcode=$("#postalcode");

@H_404_27@ var province=$("#province");

@H_404_27@ var city=$("#city");

@H_404_27@ var county=$("#county");

@H_404_27@ var but=$("#but");

@H_404_27@ var title=$("#title");

@H_404_27@ var xmlHttp; //用于保存XMLHttpRequest对象的全局变量

@H_404_27@ //用于创建XMLHttpRequest对象

@H_404_27@ function createXmlHttp() {

@H_404_27@ //根据window.XMLHttpRequest对象是否存在使用不同的创建方式

@H_404_27@ if (window.XMLHttpRequest) {

@H_404_27@ xmlHttp = new XMLHttpRequest(); //FireFox、Opera等浏览器支持的创建方式

@H_404_27@ } else {

@H_404_27@ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//IE浏览器支持的创建方式

@H_404_27@ }

@H_404_27@ }


@H_404_27@ function loadFAQCallback() {

@H_404_27@ if (xmlHttp.readyState == 4&&xmlHttp.status==200) {

@H_404_27@ var data = JSON.parse(xmlHttp.responseText).post;

@H_404_27@ if(typeof data.postalcode=="string"){

@H_404_27@ province.val(data.province);

@H_404_27@ city.val(data.city);

@H_404_27@ county.val(data.county);

@H_404_27@ }else{

@H_404_27@ title.css("display","block")

@H_404_27@ title.html("该邮政编号有误,请重新输入!");

@H_404_27@ title.hide(2000);

@H_404_27@ }

@H_404_27@ }

@H_404_27@ }

@H_404_27@ function loadFAQCallbackKeyUp() {

@H_404_27@ if (xmlHttp.readyState == 4&&xmlHttp.status==200) {

@H_404_27@ var data = JSON.parse(xmlHttp.responseText).postlist;

@H_404_27@ showPostList(data);

@H_404_27@ $("#resultlist li").mouSEOver(function(){

@H_404_27@ $(this).addClass("currentstatus");

@H_404_27@ });

@H_404_27@ $("#resultlist li").mouSEOut(function(){

@H_404_27@ $(this).removeClass("currentstatus");

@H_404_27@ });

@H_404_27@ $("#resultlist li").click(function(){

@H_404_27@ $("#postalcode").val($(this).text());

@H_404_27@ $("#resultlist").css("display","none");

@H_404_27@ });

@H_404_27@ }

@H_404_27@ }

@H_404_27@ //展示匹配列表

@H_404_27@ function showPostList(data){

@H_404_27@ $("#resultlist").css("display","block");

@H_404_27@ var len=data.length;

@H_404_27@ var liList=new Array();

@H_404_27@ var temp="";

@H_404_27@ for(i=0;i<len;i++){

@H_404_27@ temp="<li>"+data[i].postalcode+"</li>";

@H_404_27@ liList.push(temp);

@H_404_27@ }

@H_404_27@ //var list=liList.join();

@H_404_27@ //alllist==list.replace(/,/g,'');

@H_404_27@ var alllist=liList.join("");//拼接html

@H_404_27@ $("#resultlist").html(alllist);

@H_404_27@ }

@H_404_27@ //判断键盘输入是否为数字

@H_404_27@ postalcode.keypress(function(){

@H_404_27@ if(event.keyCode==13){

@H_404_27@ debugger;

@H_404_27@ $("#resultlist").css("display","none");

@H_404_27@ }else if(event.keyCode<48||event.keyCode>57){

@H_404_27@ return false;

@H_404_27@ }

@H_404_27@ });

@H_404_27@ //键盘输入一个字符时,ajax发一次请求

@H_404_27@ postalcode.keyup(function(){

@H_404_27@ if(event.keyCode>47||event.keyCode<58){

@H_404_27@ var postvalue=postalcode.val();

@H_404_27@ createXmlHttp(); //创建XmlHttpRequest对象

@H_404_27@ xmlHttp.onreadystatechange = loadFAQCallbackKeyUp;

@H_404_27@ xmlHttp.open("GET","getPostList.action?poststart="+postvalue,true);

@H_404_27@ xmlHttp.send(null);

@H_404_27@ }

@H_404_27@ });

@H_404_27@ but.click(function(){

@H_404_27@ var postalcode=$("#postalcode").val();

@H_404_27@ if(postalcode.length==0){

@H_404_27@ title.css("display","block")

@H_404_27@ title.html("输入不能为空");

@H_404_27@ title.hide(2000);

@H_404_27@ }else if (postalcode.length<6){

@H_404_27@ title.css("display","block")

@H_404_27@ title.html("请输入6位邮政编码");

@H_404_27@ title.hide(2000);

@H_404_27@ }else{

@H_404_27@ createXmlHttp(); //创建XmlHttpRequest对象

@H_404_27@ xmlHttp.onreadystatechange = loadFAQCallback;

@H_404_27@ xmlHttp.open("GET","getPost.action?post.postalcode="+postalcode,true);

@H_404_27@ xmlHttp.send(null);

@H_404_27@ }

@H_404_27@ });

@H_404_27@});

@H_404_27@</script>

@H_404_27@ </head>

@H_404_27@ <body>

@H_404_27@ <div class="top">

@H_404_27@ <center> <h3>根据邮政编码查询地址</h3></center>

@H_404_27@ <div id="titlediv"><span id="title"></span></div>

@H_404_27@ <div> <label>请输入邮政编码:</label><input type="text" id="postalcode" maxlength="6"></input></div>

@H_404_27@ <div><label>省自治区直辖市:</label><input type="text" id="province"></input></div>

@H_404_27@ <div><label>地级市:</label><input type="text" id="city"></input></div>

@H_404_27@ <div><label>县市区:</label><input type="text" id="county"></input></div>

@H_404_27@ <input type="button" id="but" value="查询"/>

@H_404_27@ </div>

@H_404_27@ <div id="resultlist">查询结果</div>

@H_404_27@ </body>

@H_404_27@</html>

处理请求的Action:PostAction.java

package com.ajax.action;


@H_404_27@import java.util.ArrayList;

@H_404_27@import com.ajax.model.Post;

@H_404_27@import com.ajax.service.PostService;

@H_404_27@import com.opensymphony.xwork2.ActionSupport;


@H_404_27@public class PostAction extends ActionSupport{

@H_404_27@ Post post;

@H_404_27@ public String poststart;

@H_404_27@ ArrayList<Post> postlist ;

@H_404_27@ public ArrayList<Post> getPostlist() {

@H_404_27@ return postlist;

@H_404_27@ }

@H_404_27@ public void setPostlist(ArrayList<Post> postlist) {

@H_404_27@ this.postlist = postlist;

@H_404_27@ }

@H_404_27@ public String getPoststart() {

@H_404_27@ return poststart;

@H_404_27@ }

@H_404_27@ public void setPoststart(String poststart) {

@H_404_27@ this.poststart = poststart;

@H_404_27@ }

@H_404_27@ PostService postservice=new PostService();

@H_404_27@public Post getPost() {

@H_404_27@ return post;

@H_404_27@ }

@H_404_27@ public void setPost(Post post) {

@H_404_27@ this.post = post;

@H_404_27@ }

@H_404_27@public String showPostInfro(){

@H_404_27@ System.out.println("hheh");

@H_404_27@ String postcodes=post.getPostalcode();

@H_404_27@ post= postservice.getPostInfro(postcodes);

@H_404_27@ return "SUCCESS";

@H_404_27@ }

@H_404_27@public String showPostListInfro(){

@H_404_27@ postlist=new ArrayList<Post>();

@H_404_27@ System.out.println("HHAHA");

@H_404_27@ postlist=postservice.getPostListInfro(poststart);

@H_404_27@ return "SUCCESS";

@H_404_27@}

@H_404_27@}

配置文件:struts.xml

@H_404_27@<?xml version="1.0" encoding="UTF-8" ?>

@H_404_27@<!DOCTYPE struts PUBLIC

@H_404_27@ "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"

@H_404_27@ "http://struts.apache.org/dtds/struts-2.1.dtd">

@H_404_27@<struts>

@H_404_27@ <constant name="struts.devMode" value="true"></constant>

@H_404_27@ <constant name="struts.custom.i18n.resources" value="faq"></constant>

@H_404_27@ <constant name="struts.i18n.encoding" value="UTF-8"></constant>

@H_404_27@ <package name="post" extends="json-default">

@H_404_27@ <action name="getPost" class="com.ajax.action.PostAction" method="showPostInfro">

@H_404_27@ <result name="SUCCESS" type="json">

@H_404_27@ </result>

@H_404_27@ </action>

@H_404_27@ <action name="getPostList" class="com.ajax.action.PostAction" method="showPostListInfro">

@H_404_27@ <result name="SUCCESS" type="json">

@H_404_27@ </result>

@H_404_27@ </action>

@H_404_27@ </package>

@H_404_27@</struts>


Model层:Post.java

@H_404_27@package com.ajax.model;


@H_404_27@public class Post {

@H_404_27@public String postalcode;

@H_404_27@public String province;

@H_404_27@public String city;

@H_404_27@public String county;

@H_404_27@public String getCounty() {

@H_404_27@ return county;

@H_404_27@}

@H_404_27@public void setCounty(String county) {

@H_404_27@ this.county = county;

@H_404_27@}

@H_404_27@public String getPostalcode() {

@H_404_27@ return postalcode;

@H_404_27@}

@H_404_27@public void setPostalcode(String postalcode) {

@H_404_27@ this.postalcode = postalcode;

@H_404_27@}

@H_404_27@public String getProvince() {

@H_404_27@ return province;

@H_404_27@}

@H_404_27@public void setProvince(String province) {

@H_404_27@ this.province = province;

@H_404_27@}

@H_404_27@public String getCity() {

@H_404_27@ return city;

@H_404_27@}

@H_404_27@public void setCity(String city) {

@H_404_27@ this.city = city;

@H_404_27@}


@H_404_27@}

Service层:PostService.java

@H_404_27@package com.ajax.service;


@H_404_27@import java.util.ArrayList;

@H_404_27@import com.ajax.dao.PostDao;

@H_404_27@import com.ajax.daoimpl.PostDaoImpl;

@H_404_27@import com.ajax.model.Post;


@H_404_27@public class PostService {

@H_404_27@ PostDao postdao=new PostDaoImpl();

@H_404_27@public Post getPostInfro(String postalcode){

@H_404_27@ return postdao.getPostInfro(postalcode);

@H_404_27@}

@H_404_27@public ArrayList<Post> getPostListInfro(String poststart) {

@H_404_27@ return postdao.getPostListInfro(poststart);

@H_404_27@}

@H_404_27@}

DAO层:PostDao.java

@H_404_27@package com.ajax.dao;


@H_404_27@import java.util.ArrayList;

@H_404_27@import com.ajax.model.Post;

@H_404_27@public interface PostDao {

@H_404_27@public Post getPostInfro(String postalcode);


@H_404_27@public ArrayList<Post> getPostListInfro(String poststart);

@H_404_27@}

DAOImpl层:PostDaoImpl.java

@H_404_27@package com.ajax.daoimpl;


@H_404_27@import java.sql.Connection;

@H_404_27@import java.sql.ResultSet;

@H_404_27@import java.sql.sqlException;

@H_404_27@import java.sql.Statement;

@H_404_27@import java.util.ArrayList;

@H_404_27@import com.ajax.dao.PostDao;

@H_404_27@import com.ajax.model.Post;

@H_404_27@import com.ajax.util.DB;


@H_404_27@public class PostDaoImpl implements PostDao {

@H_404_27@ Connection conn=null;

@H_404_27@ Statement stmt=null;

@H_404_27@ ResultSet rs=null;

@H_404_27@ /*

@H_404_27@ * 获取邮政编码对应的地址信息

@H_404_27@ * @see com.ajax.dao.PostDao#getpost()

@H_404_27@ */

@H_404_27@ public Post getPostInfro(String postalcode) {

@H_404_27@ Post post =new Post();

@H_404_27@ String sql="select distinct * from post where postalcode='"+postalcode+"'";

@H_404_27@ conn=DB.getConn();

@H_404_27@ stmt=DB.getStatement(conn);

@H_404_27@ rs=DB.getResultSet(stmt,sql);

@H_404_27@ try {

@H_404_27@ while(rs.next()){

@H_404_27@ post.setProvince(rs.getString("province"));

@H_404_27@ post.setCity(rs.getString("city"));

@H_404_27@ post.setCounty(rs.getString("county"));

@H_404_27@ post.setPostalcode(rs.getString("postalcode"));

@H_404_27@ }

@H_404_27@ } catch (sqlException e) {

@H_404_27@ e.printStackTrace();

@H_404_27@ }

@H_404_27@ System.out.println(post.getProvince());

@H_404_27@ return post;

@H_404_27@ }

@H_404_27@ /*

@H_404_27@ * 获取postlist列表

@H_404_27@ * @see com.ajax.dao.PostDao#getPostList(java.lang.String)

@H_404_27@ */

@H_404_27@ public ArrayList<Post> getPostListInfro(String poststart) {

@H_404_27@ ArrayList<Post> postlist=new ArrayList<Post>();

@H_404_27@ String sql="select * from (select * from post group by postalcode) as postdetail where postalcode like '"+poststart+"%' limit 0,10";

@H_404_27@ System.out.println(sql);

@H_404_27@ conn=DB.getConn();

@H_404_27@ stmt=DB.getStatement(conn);

@H_404_27@ rs=DB.getResultSet(stmt,sql);

@H_404_27@ try {

@H_404_27@ while(rs.next()){

@H_404_27@ Post p=new Post();

@H_404_27@ p.setPostalcode(rs.getString("postalcode"));

@H_404_27@ p.setProvince(rs.getString("province"));

@H_404_27@ p.setCity(rs.getString("city"));

@H_404_27@ p.setCounty(rs.getString("county"));

@H_404_27@ postlist.add(p);

@H_404_27@ }

@H_404_27@ } catch (sqlException e) {

@H_404_27@ e.printStackTrace();

@H_404_27@ }

@H_404_27@ System.out.println(postlist.size());

@H_404_27@ return postlist;

@H_404_27@ }

@H_404_27@}

自己封装数据库连接工具类:DB.JAVA

@H_404_27@package com.ajax.util;

@H_404_27@import java.sql.*;

@H_404_27@public class DB {

@H_404_27@ public static Connection getConn() {

@H_404_27@ Connection conn = null;

@H_404_27@ try {

@H_404_27@ Class.forName("com.MysqL.jdbc.Driver");

@H_404_27@ conn = DriverManager.getConnection("jdbc:MysqL://localhost/demo?user=root&password=root");

@H_404_27@ } catch (ClassNotFoundException e) {

@H_404_27@ e.printStackTrace();

@H_404_27@ } catch (sqlException e) {

@H_404_27@ e.printStackTrace();

@H_404_27@ }

@H_404_27@ return conn;

@H_404_27@ }

@H_404_27@ public static PreparedStatement prepare(Connection conn,String sql) {

@H_404_27@ PreparedStatement pstmt = null;

@H_404_27@ try {

@H_404_27@ if(conn != null) {

@H_404_27@ pstmt = conn.prepareStatement(sql);

@H_404_27@ }

@H_404_27@ } catch (sqlException e) {

@H_404_27@ e.printStackTrace();

@H_404_27@ }

@H_404_27@ return pstmt;

@H_404_27@ }

@H_404_27@ public static PreparedStatement prepare(Connection conn,String sql,int autoGenereatedKeys) {

@H_404_27@ PreparedStatement pstmt = null;

@H_404_27@ try {

@H_404_27@ if(conn != null) {

@H_404_27@ pstmt = conn.prepareStatement(sql,autoGenereatedKeys);

@H_404_27@ }

@H_404_27@ } catch (sqlException e) {

@H_404_27@ e.printStackTrace();

@H_404_27@ }

@H_404_27@ return pstmt;

@H_404_27@ }

@H_404_27@ public static Statement getStatement(Connection conn) {

@H_404_27@ Statement stmt = null;

@H_404_27@ try {

@H_404_27@ if(conn != null) {

@H_404_27@ stmt = conn.createStatement();

@H_404_27@ }

@H_404_27@ } catch (sqlException e) {

@H_404_27@ e.printStackTrace();

@H_404_27@ }

@H_404_27@ return stmt;

@H_404_27@ }

@H_404_27@ public static ResultSet getResultSet(Statement stmt,String sql) {

@H_404_27@ ResultSet rs = null;

@H_404_27@ try {

@H_404_27@ if(stmt != null) {

@H_404_27@ rs = stmt.executeQuery(sql);

@H_404_27@ }

@H_404_27@ } catch (sqlException e) {

@H_404_27@ e.printStackTrace();

@H_404_27@ }

@H_404_27@ return rs;

@H_404_27@ }

@H_404_27@ public static void executeUpdate(Statement stmt,String sql) {

@H_404_27@ try {

@H_404_27@ if(stmt != null) {

@H_404_27@ stmt.executeUpdate(sql);

@H_404_27@ }

@H_404_27@ } catch (sqlException e) {

@H_404_27@ e.printStackTrace();

@H_404_27@ }

@H_404_27@ }

@H_404_27@ public static void close(Connection conn) {

@H_404_27@ try {

@H_404_27@ if(conn != null) {

@H_404_27@ conn.close();

@H_404_27@ conn = null;

@H_404_27@ }

@H_404_27@ } catch (sqlException e) {

@H_404_27@ e.printStackTrace();

@H_404_27@ }

@H_404_27@ }

@H_404_27@ public static void close(Statement stmt) {

@H_404_27@ try {

@H_404_27@ if(stmt != null) {

@H_404_27@ stmt.close();

@H_404_27@ stmt = null;

@H_404_27@ }

@H_404_27@ } catch (sqlException e) {

@H_404_27@ e.printStackTrace();

@H_404_27@ }

@H_404_27@ }

@H_404_27@ public static void close(ResultSet rs) {

@H_404_27@ try {

@H_404_27@ if(rs != null) {

@H_404_27@ rs.close();

@H_404_27@ rs = null;

@H_404_27@ }

@H_404_27@ } catch (sqlException e) {

@H_404_27@ e.printStackTrace();

@H_404_27@ }

@H_404_27@ }

@H_404_27@}

数据库:数据表名: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');

相关文章

JS原生Ajax操作(XMLHttpRequest) GET请求 POST请求 兼容性问题 利用iframe模拟ajax 实现表单提交的返回...
AJAX 每日更新前端基础,如果觉得不错,点个star吧 &#128515; https://github.com/WindrunnerMax/E...
踩坑Axios提交form表单几种格式 前后端分离的开发前后端, 前端使用的vue,后端的安全模块使用的SpringSe...
很早就听闻ajax的名声,但是却一直不知道怎么用,今天自己捣鼓了一下,竟然会用了,哈哈哈哈。 为了防止...
需要在服务器上进行哈 jquery的ajax方法: // jquery请求 $.ajax({ url: &quot;./server/slider.js...
Ajax函数封装ajax.js // Get / Post // 参数 get post // 是否异步 // 如何处理响应数据 // URL // var...