>  기사  >  백엔드 개발  >  Ajax PHP에서 3단계 연결을 구현하는 방법

Ajax PHP에서 3단계 연결을 구현하는 방법

藏色散人
藏色散人원래의
2020-08-18 10:53:411860검색

3단계 연결을 구현하는 Ajax PHP 방법: 먼저 테스트 데이터베이스를 만들고 세 개의 테이블을 만든 다음 모든 지역을 초기화한 다음 최종적으로 데이터베이스를 쿼리하고 필요한 작업을 수행합니다. 처리를 표시할 수 있습니다.

Ajax PHP에서 3단계 연결을 구현하는 방법

추천: "PHP Video Tutorial"

이 사례는 데이터베이스와 관련되며 데이터베이스 디자인은 다음과 같습니다.

먼저 다음 내용으로 test데이터베이스를 생성합니다.

CREATE TABLE IF NOT EXISTS `province` (
  `province_id` int(2) NOT NULL AUTO_INCREMENT,
  `province_name` varchar(20) NOT NULL,
  PRIMARY KEY (`province_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
 
INSERT INTO `province` (`province_id`, `province_name`) VALUES
(1, '安徽'),
(2, '浙江');
 
CREATE TABLE IF NOT EXISTS `city` (
  `city_id` int(4) NOT NULL AUTO_INCREMENT,
  `city_name` varchar(20) NOT NULL,
  `province_id` int(4) NOT NULL,
  PRIMARY KEY (`city_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
 
INSERT INTO `city` (`city_id`, `city_name`, `province_id`) VALUES
(1, '合肥', 1),
(2, '安庆', 1),
(3, '南京', 2),
(4, '徐州', 2);
 
CREATE TABLE IF NOT EXISTS `county` (
  `county_id` int(4) NOT NULL AUTO_INCREMENT,
  `county_name` varchar(20) NOT NULL,
  `city_id` int(4) NOT NULL,
  PRIMARY KEY (`county_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
 
INSERT INTO `county` (`county_id`, `county_name`, `city_id`) VALUES
(1, '怀宁', 2),
(2, '望江', 2),
(3, '肥东', 1),
(4, '肥西', 1);

데이터베이스에 대한 설명: 도, 시, 군 세 개의 테이블을 만들고 여러 개의 테스트 데이터를 삽입했습니다. 물론 테이블을 디자인할 수도 있습니다. 물론 효율적입니다. . 어떤 테이블도 좋은 것이 아니므로 개인 습관에 따라 사용을 권장하지 않습니다.

구현 과정은 어렵지 않습니다. 아이디어는 다음과 같습니다.

1) 모든 지방을 초기화하면 데이터베이스에서 지방을 직접 쿼리할 수 있습니다.
2) 사용자가 선택하면 a Province 이벤트를 트리거하고 현재 지방의 idajax를 통해 서버 프로그램에 전달합니다. 형식은 클라이언트에 반환됩니다.
4) 클라이언트는 서버에서 데이터를 얻습니다. 필요한 처리를 수행하고 표시합니다
select.php 만들기 (코드는 간단합니다. 함수 구현만 하면 원리만 설명하면 됩니다! )

1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
2 <html>
3 <head>
4 <title>三级联动(作者:mckee - www.phpddt.com)</title>
5 <meta http-equiv="content-type"content="text/html; charset=UTF-8"/>
6 <script>
7 function createAjax(){
8 var xmlHttp = false;
9 if (window.XMLHttpRequest){
10 xmlHttp = new XMLHttpRequest();
11 }else if(window.ActiveXObject){
12 try{
13 xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
14 }catch(e){
15 try{
16 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
17 }catch(e){
18 xmlHttp = false;
19 }
20 }
21 }
22 return xmlHttp; 
23 }
24 
25 var ajax = null;
26 function getCity(province_id){
27 ajax = createAjax();
28 ajax.onreadystatechange=function(){
29 if(ajax.readyState == 4){
30 if(ajax.status == 200){ 
31 var cities = ajax.responseXML.getElementsByTagName("city");
32 $(&#39;city&#39;).length = 0;
33 var myoption = document.createElement("option");
34 myoption.value = "";
35 myoption.innerText = "--请选择城市--";
36 $(&#39;city&#39;).appendChild(myoption);
37 for(var i=0;i<cities.length;i++){
38 var city_id = cities[i].childNodes[0].childNodes[0].nodeValue;
39 var city_name = cities[i].childNodes[1].childNodes[0].nodeValue;
40 var myoption = document.createElement("option");
41 myoption.value = city_id;
42 myoption.innerText = city_name;
43 $(&#39;city&#39;).appendChild(myoption);
44 }
45 }
46 }
47 }
48  
49 ajax.open("post","selectPro.php",true);
50 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
51 ajax.send("province_id="+province_id);
52  
53 }
54  
55 function getCounty(city_id){
56 ajax = createAjax();
57 ajax.onreadystatechange=function(){
58 if(ajax.readyState == 4){
59 if(ajax.status == 200){
60  
61 var cities = ajax.responseXML.getElementsByTagName("county");
62 $(&#39;county&#39;).length = 0;
63 var myoption = document.createElement("option");
64 myoption.value = "";
65 myoption.innerText = "--请选择县--";
66 $(&#39;county&#39;).appendChild(myoption);
67 for(var i=0;i<cities.length;i++){
68 var city_id = cities[i].childNodes[0].childNodes[0].nodeValue;
69 var city_name = cities[i].childNodes[1].childNodes[0].nodeValue;
70 var myoption = document.createElement("option");
71 myoption.value = city_id;
72 myoption.innerText = city_name;
73 $(&#39;county&#39;).appendChild(myoption);
74 }
75 }
76 }
77 }
78 ajax.open("post","selectPro.php",true);
79 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
80 ajax.send("city_id="+city_id);
81 }
82  
83 function $(id){
84 return document.getElementById(id);
85 }
86  
87 </script>
88 </head> 
89 <body>
90 <form name="location">
91 <select name="province" onchange="getCity(this.value)">
92 <option value="">-- 请选择省份--</option>
93 <?php
94 $conn = mysql_connect("localhost","root","");
95 mysql_select_db("test");
96 mysql_query("set names utf8");
97 $sql = "select * from province"; 
98 $result = mysql_query( $sql ); 
99 while($res = mysql_fetch_assoc($result)){ 
100 ?> 
101 <option value="<?php echo $res[&#39;province_id&#39;]; ?>"><?php echo $res[&#39;province_name&#39;]?></option> 
102 <?php
103 } 
104 ?>
105 </select>
106  
107 <select name="city" id="city" onChange="getCounty(this.value)">
108 <option value="">--请选择城市--</option>
109 </select>
110  
111 <select name="county" id="county">
112 <option value="">--请选择县--</option>
113 </select>
114 </form>
115 </body>
116 </html>
selectPro.php 만들기 페이지:

117 <?php
118 //禁止缓存(www.phpddt.com原创)
119 header("Content-type:text/xml; charset=utf-8");
120 header("Cache-Control:no-cache");
121 //数据库连接
122 $conn = mysql_connect("localhost","root","");
123 mysql_select_db("test");
124 mysql_query("set names utf8");
125 
126 if(!empty($_POST[&#39;province_id&#39;])){
127 
128 $province_id = $_POST[&#39;province_id&#39;];
129 $sql = "select * from city where province_id = {$province_id}";
130 $query = mysql_query($sql);
131 $info = "<province>";
132 while($res = mysql_fetch_assoc($query)){
133 $info .= "<city>";
134 $info .= "<city_id>".$res[&#39;city_id&#39;]."</city_id>";
135 $info .= "<city_name>".$res[&#39;city_name&#39;]."</city_name>";
136 $info .= "</city>";
137 }
138 $info .= "</province>";
139 echo $info;
140 }
141 
142 if(!empty($_POST[&#39;city_id&#39;])){
143 
144 $city_id = $_POST[&#39;city_id&#39;];
145 $sql = "select * from county where city_id = {$city_id}";
146 $query = mysql_query($sql);
147 $info = "<city>";
148 while($res = mysql_fetch_assoc($query)){
149 $info .= "<county>";
150 $info .= "<county_id>".$res[&#39;county_id&#39;]."</county_id>";
151 $info .= "<county_name>".$res[&#39;county_name&#39;]."</county_name>";
152 $info .= "</county>";
153 }
154 $info .= "</city>";
155 echo $info;
156 }
157 ?>

인터페이스는 다음과 같습니다:

위 내용은 Ajax PHP에서 3단계 연결을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.