1、第一步建立一个html页面的,放置省、市、县三个select选择框,代码如下:
- <!DOCTYPE html>
- <html>
- <head>
- <title></title>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <script src="./js/jquery-1.8.3.min.js" type="text/javascript"></script>
- <script type="text/javascript">
- $(document).ready(function() {
- // 加载所有的省份
- $.ajax({
- type: "get",
- url: "region_action.php", // type=1表示查询省份
- data: {"parent_id": "1", "type": "1"},
- dataType: "json",
- success: function(data) {
- $("#provinces").html("<option value=''>请选择省份</option>");
- $.each(data, function(i, item) {
- $("#provinces").append("<option value='" + item.region_id + "'>" + item.region_name + "</option>");
- });
- }
- });
- $("#provinces").change(function() {
- $.ajax({
- type: "get",
- url: "region_action.php", // type =2表示查询市
- data: {"parent_id": $(this).val(), "type": "2"},
- dataType: "json",
- success: function(data) {
- $("#citys").html("<option value=''>请选择市</option>");
- $.each(data, function(i, item) {
- $("#citys").append("<option value='" + item.region_id + "'>" + item.region_name + "</option>");
- });
- }
- });
- });
- $("#citys").change(function() {
- $.ajax({
- type: "get",
- url: "region_action.php", // type =2表示查询市
- data: {"parent_id": $(this).val(), "type": "3"},
- dataType: "json",
- success: function(data) {
- $("#countys").html("<option value=''>请选择县</option>");
- $.each(data, function(i, item) {
- $("#countys").append("<option value='" + item.region_id + "'>" + item.region_name + "</option>");
- });
- }
- });
- });
- });
- </script>
- </head>
- <body>
- <div>
- 省份:
- <select id="provinces">
- <option value="">请选择省份</option>
- </select>
- 市:
- <select id="citys">
- <option value="">请选择市</option>
- </select>
- 县:
- <select id="countys">
- <option value="">请选择县</option>
- </select>
- </div>
- </body>
- </html>
第二步:建立一个处理请求的PHP文件,如下:
- <?php
- require_once './Config/config.php';
- require_once './plugins/DBHelper.php';
- $type = isset($_GET["type"]) ? $_GET["type"] : "";
- $parent_id = isset($_GET["parent_id"]) ? $_GET["parent_id"] : "";
- // 链接数据库
- if ($type == "" || $parent_id == "") {
- exit(json_encode(array("flag" => false, "msg" => "查询类型错误")));
- } else {
- // 链接数据库
- $db = new DBHelper("localhost", "root", "root", "region");
- $provinces = $db->getSomeResult("global_region", "region_id,region_name", "parent_id={$parent_id} and region_type={$type}");
- $provinces_json = json_encode($provinces);
- exit($provinces_json);
- }
- ?>
第三步:其实这一步也是前提,就是要在mysql数据库中建一个地区表,此表结构简单,但是数据很多,大概3千多条,先列出表结构,具体数据请看代码附件。
- CREATE TABLE `global_region` (
- `region_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
- `parent_id` smallint(5) unsigned NOT NULL DEFAULT '0',
- `region_name` varchar(120) NOT NULL DEFAULT '',
- `region_type` tinyint(1) NOT NULL DEFAULT '2',
- PRIMARY KEY (`region_id`),
- KEY `parent_id` (`parent_id`),
- KEY `region_type` (`region_type`)
- ) ENGINE=MyISAM AUTO_INCREMENT=3409 DEFAULT CHARSET=utf8;
最终结果如下: