Home  >  Article  >  Backend Development  >  PHP+Ajax+JS three-level linkage between provinces and municipalities_PHP tutorial

PHP+Ajax+JS three-level linkage between provinces and municipalities_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:29:31670browse

The basic idea is: dynamically create the option of the select control in JS, and obtain the province and city information obtained from the SQL database in PHP through Ajax. The code is a bit long, but many of them are similar. , for example, the methods for obtaining provinces, cities, and districts in JS are similar, and in PHP, different select statements are executed through different parameters.

index.html code:

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >


PHP+Ajax to get SQL database</ title><br> <META http-equiv=Content-Type content="text/html; charset=gb2312"><br> <script src="scripts/thumbnails.js" type="text/javascript" ></script><br></head></p> <p><body></p> <p> <div id="description"><br> <select><strong>thumbnails.js code: </strong></span> ​ ​ window.onload = getProvince; ​ function createRequest() {//Ajax requires objects for PHP interaction try { Request = new XMLHttpRequest();//Create a new request object; } catch (tryMS) { Try { Request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (otherMS) {          try { ​​​​request = new ActiveXObject("Microsoft.XMLHTTP");         } catch (failed) { ​​​​request = null; } } } return request; } ​ function sech(id) {//Triggered when province and city change, select onchange event ​ var aa = document.getElementById(id); if(id=="sheng"){ GetCity(aa.value);//Here aa.value is the id of the province } if(id=="shi") { getCounty(aa.value);//here aa.value is the id of the city } ​ } ​ function getProvince() {//Get all provinces request = createRequest(); if (request == null) { alert("Unable to create request"); Return; } var url= "getDetails.php?ID=0";//When ID=0 is passed to PHP, let it get all provinces request.open("GET", url, true); request.onreadystatechange = displayProvince; //Set the callback function request.send(null); //Send request } ​ function getCity(id){//Get the city corresponding to the province request = createRequest(); if (request == null) { alert("Unable to create request"); Return; } var url= "getDetails.php?ID=" + escape(id); request.open("GET", url, true); request.onreadystatechange = displayCity; request.send(null); } ​ function getCounty(id){//Get the district corresponding to the city request = createRequest(); if (request == null) { alert("Unable to create request"); Return; } var url= "getDetails.php?ID=" + escape(id); request.open("GET", url, true); request.onreadystatechange = displayCounty; request.send(null); } ​ ​ function displayProvince() {//Dynamicly add the acquired data to select if (request.readyState == 4) { If (request.status == 200) { var a=new Array; var b=request.responseText;//Assign the data returned by PHP to b a=b.split(",");//Save this data in array a through "," document.getElementById("sheng").length=1; var obj=document.getElementById("sheng'); for(i=0;i Obj.options.add(new Option(a[i],i+1)); //Dynamicly generate OPTION and add it to select. The first parameter is Text and the second parameter is Value. ​ } } } ​ ​ function displayCity() {//Dynamicly add the acquired data to select if (request.readyState == 4) { If (request.status == 200) { var a=new Array; var b=request.responseText; a=b.split(","); document.getElementById("shi").length=1;//Reselect document.getElementById("xian").length=1; //Reselect if(document.getElementById("sheng").value!="province"){ var obj=document.getElementById('shi'); for(i=0;i obj.options.add(new Option(a[i], document.getElementById("sheng").value*100+i+1)); //ocument.getElementById("sheng").value*100+i+ 1 corresponds to the city ID. } ​​ } } } ​ function displayCounty() {//Add the obtained data to select if (request.readyState == 4) { If (request.status == 200) { var a=new Array; var b=request.responseText; a=b.split(","); document.getElementById("xian").length=1; if(document.getElementById("sheng").value!="province"&&document.getElementById("shi").value!="city"){ var obj=document.getElementById('xian'); for(i=0;i Obj.options.add(new Option(a[i],i+1001)); } ​​ } } } ​ <span><strong>getDetails.php code: </strong></span> ​ <p><?php<br /> header("Content-Type: text/html; charset=gb2312");<br /> $conn = new COM("ADODB.Connection") or die("Cannot start ADO" );<br />$connstr = "Provider=SQLOLEDB;Persist Security Info=False;User ID=sa;Password=zzh;Initial Catalog=NoteBook;Data Source=localhost"; <br /> <br />if($_REQUEST['ID']= =0){//Get the list of provinces<br />$conn->Open($connstr); //Establish a database connection<br> $sqlstr = "select name from Province"; //Set the query string<br> $rs = $conn->Execute($sqlstr); //Execute the query to obtain the results<br> $num_cols = $rs->Fields->Count(); //Get the number of columns in the data set<br> $ Province=array();<br> $i=0;<br> while (!$rs->EOF) {<br> $Province[$i]=$rs->Fields['name']- >Value.","; <br> $rs->MoveNext(); <br> $i++; <br> }<br> foreach($Province as $val)<br> echo $val;<br> $conn->Close();<br> $rs = null;<br> $conn = null; <br> }<br> <br> <br> <br>if($_REQUEST['ID' ]>0&&$_REQUEST['ID']<35){//Get the list of cities corresponding to the province<br />$conn->Open($connstr); //Establish a database connection<br> $sqlstr = " select name from City where cid=".$_REQUEST['ID']; //Set query string<br> $rs = $conn->Execute($sqlstr); //Execute query to get results<br> $ num_cols = $rs->Fields->Count(); //Get the number of columns in the data set<br> $City=array();<br> $i=0;<br> while (!$rs-> ;EOF) {<br> $City[$i]=$rs->Fields['name']->Value.","; <br> $rs->MoveNext(); <br> $ i++; <br> }<br> foreach($City as $val)<br> echo $val;<br> $conn->Close();<br> $rs = null;<br> $conn = null; <br> }<br> <br> <br> <br>if($_REQUEST['ID']>100){//Get the county list corresponding to the province and city<br>$conn->Open ($connstr); //Establish a database connection<br> $sqlstr = "select name from County where cid=".$_REQUEST['ID']; //Set the query string<br> $rs = $conn-> ;Execute($sqlstr); //Execute the query to get the results<br> $num_cols = $rs->Fields->Count(); //Get the number of columns in the data set<br> $County=array();<br> $i=0;<br> while (!$rs->EOF) {<br> $County[$i]=$rs->Fields['name']->Value."," ; <br> $rs->MoveNext(); <br> $i++; <br> }<br> foreach($County as $val)<br> echo $val;<br> $conn->Close ();<br> $rs = null;<br> $conn = null; <br> }<br>?></p> ​ ​ <span><strong>Database design, tables Province table, City table, County table. </strong></span> Requirements: The Province table requires id and name. The id is recommended to be from 1 to 34. For example, the id of Beijing is 1, the id of Guangdong is 2, and so on; The City table requires id, name and cid. The id is cid*100+1, and the cid is the superior of the city. For example, the superior of Shenzhen is Guangdong Province, and if the cid is 2, the id of Shenzhen is 201, and so on. The County table requires id, name and cid. Because it is a three-level relationship, the id can be arbitrary. It is recommended to increase it from 10001. The cid is the superior level. For example, the cid of Baoan District is 201, and the cid of Longgang District is also 201; ​ ​ <span><strong>Screenshot: </strong></span> ​ HTML effect: <img src="http://www.bkjia.com/uploads/allimg/140525/12395211G-0.jpg" alt=""> The result after completion: <img src="http://www.bkjia.com/uploads/allimg/140525/12395241B-1.jpg" alt=""><img src="http://www.bkjia.com/uploads/allimg/140525/123952MF-2.jpg" alt=""><img src="http://www.bkjia.com/uploads/allimg/140525/123952AH-3.jpg" alt=""> ​ ​ Note: PHP is server-side. It is recommended to debug through IP after publishing the website. <p align="left"></p> <div style="display:none;"> <span id="url" itemprop="url">http://www.bkjia.com/PHPjc/775949.html</span><span id="indexUrl" itemprop="indexUrl">www.bkjia.com</span><span id="isOriginal" itemprop="isOriginal">true</span><span id="isBasedOnUrl" itemprop="isBasedOnUrl">http: //www.bkjia.com/PHPjc/775949.html</span><span id="genre" itemprop="genre">TechArticle</span><span id="description" itemprop="description">The basic idea is: dynamically create the option of the select control in JS, and obtain the province obtained from the SQL database in PHP through Ajax Urban information, the code is a bit long, but many are similar, such as JS Zhongsheng...</span> </div> <div class="art_confoot"></div></div><div class="nphpQianMsg"><div class="clear"></div></div><div class="nphpQianSheng"><span>Statement:</span><div>The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn</div></div></div><div class="nphpSytBox"><span>Previous article:<a class="dBlack" title="PHP tips: How to use the JS and CSS optimization tool Minify_PHP tutorial" href="http://m.php.cn/faq/295383.html">PHP tips: How to use the JS and CSS optimization tool Minify_PHP tutorial</a></span><span>Next article:<a class="dBlack" title="PHP tips: How to use the JS and CSS optimization tool Minify_PHP tutorial" href="http://m.php.cn/faq/295385.html">PHP tips: How to use the JS and CSS optimization tool Minify_PHP tutorial</a></span></div><div class="nphpSytBox2"><div class="nphpZbktTitle"><h2>Related articles</h2><em><a href="http://m.php.cn/article.html" class="bBlack"><i>See more</i><b></b></a></em><div class="clear"></div></div><ul class="nphpXgwzList"><li><b></b><a href="http://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/2.html" title="All expression symbols in regular expressions (summary)" class="aBlack">All expression symbols in regular expressions (summary)</a><div class="clear"></div></li></ul></div></div><div class="nphpFoot"><div class="nphpFootBg"><ul class="nphpFootMenu"><li><a href="http://m.php.cn/"><b class="icon1"></b><p>Home</p></a></li><li><a href="http://m.php.cn/course.html"><b class="icon2"></b><p>Course</p></a></li><li><a href="http://m.php.cn/wenda.html"><b class="icon4"></b><p>Q&A</p></a></li><li><a href="http://m.php.cn/login"><b class="icon5"></b><p>My</p></a></li><div class="clear"></div></ul></div></div><div class="nphpYouBox" style="display: none;"><div class="nphpYouBg"><div class="nphpYouTitle"><span onclick="$('.nphpYouBox').hide()"></span><a href="http://m.php.cn/"></a><div class="clear"></div></div><ul class="nphpYouList"><li><a href="http://m.php.cn/"><b class="icon1"></b><span>Home</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/course.html"><b class="icon2"></b><span>Course</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/article.html"><b class="icon3"></b><span>Article</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/wenda.html"><b class="icon4"></b><span>Q&A</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/dic.html"><b class="icon6"></b><span>Dictionary</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/course/type/99.html"><b class="icon7"></b><span>Manual</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/xiazai/"><b class="icon8"></b><span>Download</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/faq/zt" title="Topic"><b class="icon12"></b><span>Topic</span><div class="clear"></div></a></li><div class="clear"></div></ul></div></div><div class="nphpDing" style="display: none;"><div class="nphpDinglogo"><a href="http://m.php.cn/"></a></div><div class="nphpNavIn1"><div class="swiper-container nphpNavSwiper1"><div class="swiper-wrapper"><div class="swiper-slide"><a href="http://m.php.cn/" >Home</a></div><div class="swiper-slide"><a href="http://m.php.cn/article.html" class="hover">Article</a></div><div class="swiper-slide"><a href="http://m.php.cn/wenda.html" >Q&A</a></div><div class="swiper-slide"><a href="http://m.php.cn/course.html" >Course</a></div><div class="swiper-slide"><a href="http://m.php.cn/faq/zt" >Topic</a></div><div class="swiper-slide"><a href="http://m.php.cn/xiazai" >Download</a></div><div class="swiper-slide"><a href="http://m.php.cn/game" >Game</a></div><div class="swiper-slide"><a href="http://m.php.cn/dic.html" >Dictionary</a></div><div class="clear"></div></div></div><div class="langadivs" ><a href="javascript:;" class="bg4 bglanguage"></a><div class="langadiv" ><a onclick="javascript:setlang('zh-cn');" class="language course-right-orders chooselan " href="javascript:;"><span>简体中文</span><span>(ZH-CN)</span></a><a onclick="javascript:;" class="language course-right-orders chooselan chooselanguage" href="javascript:;"><span>English</span><span>(EN)</span></a><a onclick="javascript:setlang('zh-tw');" class="language course-right-orders chooselan " href="javascript:;"><span>繁体中文</span><span>(ZH-TW)</span></a><a onclick="javascript:setlang('ja');" class="language course-right-orders chooselan " href="javascript:;"><span>日本語</span><span>(JA)</span></a><a onclick="javascript:setlang('ko');" class="language course-right-orders chooselan " href="javascript:;"><span>한국어</span><span>(KO)</span></a><a onclick="javascript:setlang('ms');" class="language course-right-orders chooselan " href="javascript:;"><span>Melayu</span><span>(MS)</span></a><a onclick="javascript:setlang('fr');" class="language course-right-orders chooselan " href="javascript:;"><span>Français</span><span>(FR)</span></a><a onclick="javascript:setlang('de');" class="language course-right-orders chooselan " href="javascript:;"><span>Deutsch</span><span>(DE)</span></a></div></div><script> var swiper = new Swiper('.nphpNavSwiper1', { slidesPerView : 'auto', observer: true,//修改swiper自己或子元素时,自动初始化swiper observeParents: true,//修改swiper的父元素时,自动初始化swiper }); </script></div></div><!--顶部导航 end--><script>isLogin = 0;</script><script type="text/javascript" src="/static/layui/layui.js"></script><script type="text/javascript" src="/static/js/global.js?4.9.47"></script></div><script src="https://vdse.bdstatic.com//search-video.v1.min.js"></script><link rel='stylesheet' id='_main-css' href='/static/css/viewer.min.css' type='text/css' media='all'/><script type='text/javascript' src='/static/js/viewer.min.js?1'></script><script type='text/javascript' src='/static/js/jquery-viewer.min.js'></script><script>jQuery.fn.wait = function (func, times, interval) { var _times = times || -1, //100次 _interval = interval || 20, //20毫秒每次 _self = this, _selector = this.selector, //选择器 _iIntervalID; //定时器id if( this.length ){ //如果已经获取到了,就直接执行函数 func && func.call(this); } else { _iIntervalID = setInterval(function() { if(!_times) { //是0就退出 clearInterval(_iIntervalID); } _times <= 0 || _times--; //如果是正数就 -- _self = $(_selector); //再次选择 if( _self.length ) { //判断是否取到 func && func.call(_self); clearInterval(_iIntervalID); } }, _interval); } return this; } $("table.syntaxhighlighter").wait(function() { $('table.syntaxhighlighter').append("<p class='cnblogs_code_footer'><span class='cnblogs_code_footer_icon'></span></p>"); }); $(document).on("click", ".cnblogs_code_footer",function(){ $(this).parents('table.syntaxhighlighter').css('display','inline-table');$(this).hide(); }); $('.nphpQianCont').viewer({navbar:true,title:false,toolbar:false,movable:false,viewed:function(){$('img').click(function(){$('.viewer-close').trigger('click');});}}); </script></body></html>