Ajax-ajax实例2-根据邮政编码获取地区信息

项目结构

运行效果:

数据库:

/*
SQLyog Ultimate v12.09 (64 bit)
MySQL - 5.5.53 : Database - ajaxexample_2
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`ajaxexample_2` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `ajaxexample_2`;

/*Table structure for table `postalcode` */

DROP TABLE IF EXISTS `postalcode`;

CREATE TABLE `postalcode` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `area` varchar(255) NOT NULL COMMENT '省份',
  `city` varchar(255) NOT NULL COMMENT '城市',
  `code` varchar(6) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

/*Data for the table `postalcode` */

insert  into `postalcode`(`id`,`area`,`city`,`code`) values (1,'北京','北京','100000'),(2,'北京','通县','101100'),(3,'北京','昌平','102200'),(4,'上海','上海','200000'),(5,'河南','郑州','450000');

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

AjaxRequest.js:参见博客【Ajax类

DBUtil.java:数据库工具类:

package com.gordon.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtil {
	
	private static final String URL = "jdbc:mysql://localhost:3306/ajaxexample_2";
	private static final String DRIVER = "com.mysql.jdbc.Driver";
	private static final String USERNAME = "root";
	private static final String PASSWORD = "root";

	public static Connection getConnection() throws ClassNotFoundException, SQLException {
		Class.forName(DRIVER);
		return DriverManager.getConnection(URL, USERNAME, PASSWORD);
	}
}

GetPostalcode.java 获取邮编信息servlet:

package com.gordon.servlet;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gordon.service.GetDetailByPostalCode;

/**
 * Servlet implementation class GetPostalcode
 */
@WebServlet(urlPatterns = { "/GetPostalcode" })
public class GetPostalcode extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetPostalcode() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String result = "";
		
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/text;charset=utf-8;");
		
		String postalcode = request.getParameter("postalcode");
		
		try {
			result = GetDetailByPostalCode.getContentByPostid(postalcode);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		response.getWriter().print(result);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

GetDetailByPostalCode:根据邮编获取详细到信息:

package com.gordon.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.gordon.util.DBUtil;

public class GetDetailByPostalCode {
	public static String getContentByPostid(String postalcode) throws ClassNotFoundException, SQLException {
		
		String result = "";
		
		String sql = "SELECT * FROM postalcode WHERE code = ?";
		
		Connection conn = DBUtil.getConnection();
		PreparedStatement pst = conn.prepareStatement(sql);
		
		pst.setString(1, postalcode);
		
		ResultSet rs = pst.executeQuery();
		while(rs.next()) {
			result = rs.getString("area") + "|" + rs.getString("city");
		}
	
		rs.close();
		pst.close();
		conn.close();
		
		return result;
	}
}

register.jap:注册页面:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="">
		邮编:<input type="text" id="code" oninput="keypress(this)" onblur="getPostalCode()"><br />
		地区:<input type="text" id="area"><br /> 城市:<input type="text" id="city">
	</form>
</body>

<script type="text/javascript" src="js/AjaxRequest.js"></script>

<script type="text/javascript">
	// 实例化XMLHttpRequest对象
	var xhr = Ajax();

	// 限制只能输入数字
	function keypress(_this) {
		_this.value = _this.value.replace(/[^0-9]/g, '');
	}

	// 失去焦点触发事件
	function getPostalCode() {
		var postalcode = document.getElementById("code").value;

		if (postalcode == "" || postalcode.length != 6) {
			alert("请输入正确邮编!");
		} else {
			handleGetPostalcode(postalcode);
		}
	}

	// 获取邮编相关的地区和城市
	function handleGetPostalcode(postalcode) {
		var url = "GetPostalcode";
		var params = "postalcode=" + postalcode;

		var des_url = url + "?nocache=" + new Date().getTime() + "&" + params;

		xhr.get(des_url, function(data) {
			deal_result(data);
		});
	}

	// 处理返回数据
	function deal_result(data) {

		document.getElementById("area").value = "";
		document.getElementById("city").value = "";

		if (data == "") {
			return;
		}

		var content = data.split("|");
		document.getElementById("area").value = content[0];
		document.getElementById("city").value = content[1];
	}
</script>

</html>

+++++++++++++++++++++++++++

参考:ajax实用案例大全-1动态加载数据  https://wenku.baidu.com/view/c7897bf4700abb68a982fb91.html

原文地址:https://www.cnblogs.com/hfultrastrong/p/7278527.html