本文介绍了创建动态下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我现在正在搜索互联网已经有相当一段时间找到一个正确的解决方案,但我迄今为止还没有成功。 我试图达到的目标:我创建一个动态的下拉框与省份。一旦用户选择一个动态创建的条目,区域的第二个动态下拉框只能根据所选省显示适当的条目。 因此我建立以下代码: search.php // $ i正在运行到最大省份 //每个省份在html中应该有一个选项 //会话数组provinceresults包含key1,key2,省(英语),省(其他语言)($ i = 0; $ i< $ countProvinces; $ i ++){ echo< option value =$ _ SESSION ['citiesresults'] [$ i] [0]。onClick = \removeSelected(\。$ i.\)\>。$ _ SESSION ['citiesresults'] [$ i] [1] < /选项>中; } 在body.php的正文部分我有以下JavaScript代码当我选择每个onClick的上述生成的选项之一时,将被执行: <! - 需要调用的Javascript每个onClick事件的dynamic_drop_down.php函数 - > < script type = \text / javascript\> function removeUnselected($ key){ document.getElementById(\php_code\)。innerHTML = \<?php / /从pdo.vhd $ districtsSelected = removeUnselected(。$ _ SESSION ['citiesresults'] [$ key] [0]。)); } ?> \; } 我需要从$第一个PHP部分获取$ i计数器到Javascript函数。 之后,我需要填充的$ districtsSelected进一步使用我的search.php php函数removeUnselected(。$ _ SESSION ['citiesresults'] [ $键] [0]);看起来像这样,并且包含在search.php中: <?php / * * *此php文件用于检索所选省份的区域。 *此文件由search.php调用。 *作为输入,函数需要使用所选省的ID进行调用,它将返回所有相关的区域。 * / 函数removeUnselected($ provinceKey){ //构建返回所需区域的数组 $ districtsSelected = array(); //通过get_value_help.php 循环遍历数据库中的所有区域($ i = 0; $ i //检查表dbo.vhp中的省ID是否与表中的id匹配dbo.vhd if(strcmp($ provinceKey ,$ _SESSION ['districtsresults'] [$ i] [1])== 0){ //如果语言设置为英文,返回英文区名 if( $ _SESSION ['lng'] ==english){ //删除未选择的所有区域 $ districtsSelected [] = $ _SESSION ['districtsresults'] [$ i ] [2]; } //如果语言设置为khmer elseif($ _SESSION ['lng'] ==khmer),返回khmer中的区域名称{ //删除未选择的区域 $ districtsSelected [] = $ _SESSION ['districtsresults'] [$ i] [3]; } } } //返回结果 return($ districtsSelected); } ?> 非常感谢任何关于如何以正常工作方式构建此建议的建议! 谢谢你,问候, codac 编辑:我使用以下JavaScript: http://www.mattkruse。 com / javascript / dynamicoptionlist / index.html 我现在有两个问题:由于有24个省,86个地区,1600个公社和13500个村庄,为下拉框创建需要几秒钟。 表格如下(省份): country_id province_id province_en province_kh 000000 010000 Banteay Mean Chey Khmer 1 000000 020000蝙蝠丹邦高棉2 000000 030000 Kampong Cham Khmer 3 000000 040000 Kampong Chhnang Khmer (区) prov ince_id district_id district_en district_kh 010000 010200 Mongkol Borei Khmer 1 010000 010300 Phnum Srok Khmer 2 010000 010400 Preah Netr Preah Khmer 3 010000 010500 Ou Chrov Khmer 4 ...相同的公社和村庄。 我通过以下方式获取Microsoft SQL Server中的值: $ sqlProvinces =SELECT country_id,province_id,province_en,province_kh FROM dbo.vhp; $ sqlDistricts =SELECT province_id,district_id,district_en,district_kh FROM dbo.vhd; ...公社和村庄相同。 像我在评论中提到的那样,我将这些值存储在$ _SESSION中: $ _ SESSION [citiesresults] = $ provincesResults; $ _SESSION [districtsresults] = $ districtsResults;之后,我使用函数dyndrpdwn.php来生成下拉列表: > <?php 函数dyndrpdwn(){ //计数 $ countProvinces = count($ _ SESSION [citiesresults])的省份,地区,公社和村庄的数量; $ countDistricts = count($ _ SESSION [districtsresults]); $ countCommunes = count($ _ SESSION [communesresults]); $ countVillages = count($ _ SESSION [villagesresults]); // NULL返回值 $ returnPD = NULL; $ returnC = NULL; $ returnV = NULL; $ defaultP = NULL; $ defaultD = NULL; $ defaultC = NULL; $ defaultV = NULL; //将计数器的起始值设置为0 $ j = 0; $ k = 0; $ l = 0; //启动JavaScript并创建DynamitOptionList $ returnPD =< script type = \text / javascript\> var makeGeo = new DynamicOptionList (\ provinces\,\ districts\,\ communes\,\ villages\);; //循环遍历所有省($ i = 0; $ i $ $ countProvinces; $ i ++){ //创建选项列表省 $ returnPD = $ returnPD。makeGeo.forValue(\。$ _ SESSION [citiesresults] [$ i] [1]。\)。addOptionsTextValue(; //为区域创建选项列表(while如果比for更强大)!),并确保计数器没有脱离索引 while($ j $ returnPD = $ returnPD。\ [districtsresults ] [$ j]的[2]。 \,\ $ _ SESSION [ districtsresults] [$ d] [1] \,$ _ SESSION。。 $$ $ $ $ $ $ $ $ $ $ $ $ $ $$ $ $ $ $ $ $ $ $ $ $ $ _ SESSION [districtsresults] [$ j] [1]。\)。addOptionsTextValue(; //为公社创建选项列表(while如果更多的perf ormant thanfor!),并确保计数器没有脱离索引 while($ k $ returnC = $ returnC。\ $ _ SESSION [ communesresults] [$ k]的[2]。 \,\ $ _ SESSION [ communesresults] [$ k]的[1] \,。; $$ $ $ $ $ $ $ $ $ $ $$ $ $ $ $ $ $ $ $ $ $ $ $ _ SESSION [ districtsresults] [$ d] [1]。 \)。forValue(\ 。$ _ SESSION [ communesresults] [$ k]的[1]。 \) .addOptionsTextValue(; //为村庄创建选项列表(while如果比for更强大)!),并确保计数器没有脱离索引 while( $ l $ returnV = $ returnV。\$ _ SESSION [villagesresults] [$ l] [2]。\,\$ _ SESSION [villagesresults] [$ l] [1 ]\,; //设置默认值 $ defaultV =makeGeo.forValue(\。$ _ SESSION [communesresults] [$ k ] [1]。\)。setDefaultOptions(\。$ _ SESSION [searchresultspmd] [0] [8]。\);; //增加柜台1 $ l ++; } //剪切最后一个值$ returnC $ returnV = substr($ returnV,0)之后的字符串的最后一个,-1); //关闭JavaScript语句 $ returnV = $ returnV。);; //如果没有公社的村庄,请删除已经准备好的字符串makeGeo.forValue(\。$ _ SESSION [citiesresults] [$ i] [1]。 \ )。forValue(\。$ _ SESSION [ districtsresults] [$ d] [1]。 \)。forValue(\ 。$ _ SESSION [ communesresults] [$ķ ] [1]。\)。addOptionsTextValue( if(substr($ returnV,-21)==addOptionsTextValue);){ $ returnV = $ returnV,0,-86); } //设置默认值 $ defaultC =makeGeo.forValue(\。$ _ SESSION [districtsresults] [$ j] [1] 。 \)setDefaultOptions(\ [searchresultspmd ] [0] [7]。 \。$ _ SESSION。 );; //将计数器增加1 $ k ++; } //剪切最后一个值$ returnC $ returnC = substr($ returnC,0,-1)之后的字符串的最后一个,; //关闭JavaScript语句 $ returnC = $ returnC。);; //如果没有该区的公社,请删除已经准备好的字符串makeGeo.forValue(\。$ _ SESSION [citiesresults] [$ i] [1]。 \\$$($($ returnC,-21))($($ returnC,-21) ==addOptionsTextValue;){ $ returnC = substr($ returnC,0,-66); } //设置默认值 $ defaultD =makeGeo.forValue(\。$ _ SESSION [citiesresults] [$ i] [1] 。 \)setDefaultOptions(\ [searchresultspmd ] [0] [8]。 \。$ _ SESSION。 );; //将计数器增加1 $ j ++; } //剪切最后一个值为$ returnPD $ returnPD = substr($ returnPD,0,-1)的字符串的最后一个,; //关闭JavaScript语句 $ returnPD = $ returnPD。);; //如果省份没有区域,请删除已经准备好的字符串makeGeo.forValue(\。$ _ SESSION [citiesresults] [$ i] [1]。 if(substr($ returnPD,-21)==addOptionsTextValue);){ $ returnPD = substr($ returnPD,0, - 47); } //设置默认值 $ defaultP =makeGeo.forValue(\cities \)。setDefaultOptions(\$ _ SESSION [ provincesresults] [$ i] [1] \);; } //将省,区,公社和村庄放在一起,并关闭Javascript $ returnPDCV = $ returnPD。$ returnC。$ returnV。$ defaultD。$ defaultC。 $ defaultV < /脚本> 中。 //返回结果返回sprintf($ returnPDCV); } ?> 为了使用JavaScript,我在patient_update.php中使用以下代码: //包含动态下拉生成器 include(/ functions / dyndrpdwn.php); <! - 为动态下拉列表添加JavaScript - > < script type = \text / javascript\src = \/js/dynamicoptionlist.js\>< / script> //调用动态下拉函数 echo dyndrpdwn(); echo<! - 省创建下拉字段 - > < select name = \cities\class = \dropdown\ >中; //当get_value_help.php收到数据或者会话数组已经被填充 if(isset($ _ GET [value])==true时,填写下拉列表& $ _GET [value] ==receive|| isset($ _ SESSION [citiesresults])==true&& count($ _ SESSION [citiesresults])> 0){ //从pdo.vhd中获取省数组中的所有值 $ countProvinces = count($ _ SESSION [citiesresults]); for($ i = 0 ; $ i< $ countProvinces; $ i ++){ //根据网站设置显示高棉语或英语。 $ _SESSION [searchresultspmd] [0] [5])= dbo.pmd中的province_id // $ _ SESSION [citiesresults] [$ i] [1] = dbo.vhp中的province_id if(isset($ _ SESSION [lng])==true){ switch($ _SESSION [lng]){ caseenglish : if($ _ SESSION [citiesresults] [$ i] [2] == $ _SESSION [searchresultspmd] [0] [5]){ echo< option value =。$ _ SESSION [citiesresults] [$ i] [1]。SELECTED>; } else { echo< option value =。$ _ SESSION [citiesresults] [$ i] [1]。>; } echo$ _ SESSION [citiesresults] [$ i] [2]。< / option>; break; casekhmer: if($ _ SESSION [citiesresults] [$ i] [2] == $ _SESSION [searchresultspmd] [0] [ 5]){ echo< option value =。$ _ SESSION [citiesresults] [$ i] [1]。SELECTED>; } else { echo< option value =。$ _ SESSION [citiesresults] [$ i] [1]。>; } echo$ _ SESSION [citiesresults] [$ i] [3]。< / option>; break; } } } } echo< / select> < / td> < td> <! - 区创建下拉字段 - > < select name = \districts\class = \dropdown\ > < script type = \text / javascript\> makeGeo.printOptions(\districts\)< / script> < / select> < / td> < td> <! - 创建下拉字段 - > < select name = \communes\class = \dropdown\> < script type = \text / javascript\> makeGeo.printOptions (\communes\)< / script> < / select> < / td> < td> <! - 村庄创建下拉字段 - > < select name = \villages\class = \dropdown\> < script type = \text / javascript\> makeGeo.printOptions(\villages\)< / script> < / select> < / td> ... 所以有现在有两个问题: 调用dyndrpdwn.php函数需要很长的时间,因为有〜24个省,〜86个区,〜 1600个公社和〜13500个村庄环绕着他们。有没有办法提高性能? 使用 setDefaultOptions 我尝试设置默认值为正确的下拉列表。但在我的代码中,它不起作用。我已经将其与[JavaScript网站] [1]上的示例进行了比较,但我找不到错误...你能看出为什么它不能像我这样做吗? 结果目前是这样的: <脚本类型= 文本/ JavaScript的 > var makeGeo = new DynamicOptionList(cities,district,communes,village); 这将创建省份和地区的条目: addOptionsTextValue(Mongkol Borei,010200,Phnum Srok,010300,Preah Netr Preah,010400), makeGeo.forValue ,0105,u i Sa,010600,ma Pu Pu,010700,S ay,010800,马来,010900); 创建公社的条目 makeGeo.forValue(010000)forValue(010200)。addOptionsTextValue(Banteay Neang,010201,Bat Trang,010202,Chamnaom 010203,Kouk Ballangk,010204,Koy Maeng,010205,Ou Prasat,010206,Phnum Touch,010207,Rohat Tuek,010208 010209,Sambuor,010210,Soea,010211,Srah Reang,010212,Ta Lam,010213); 这将为村庄创建条目: makeGeo.forValue(010000)forValue(010200)forValue(010201)。addOptionsTextValue(Ou Thum,01020101,Phnum 01020102,Banyay Neang,01020103,Kouk Pnov,01020104,Trang,01020105,Pongro,01020106,Kouk Tonloab,01020107,Trabaek 01020108,Khile,01020109,Samraong Pen,01020110,Dang Run Lech,01020111,Dang Run Kaeut,01020112,Ou Snguot,01020113 0101,01020114,Oy Andoung Lech,01020116,Ou Andoung Kandal,01020117,Ou Andoung Kaeut,01020118, Kouk Kduoch,01020119); 这应该为省,区和公社设置默认值(只有3个例子;他们到目前为止...): makeGeo.forValue(240000)。setDefaultOptions(Boeng Trakuon) ; makeGeo.forValue(240200)。setDefaultOptions(Ou Andoung); makeGeo.forValue(240204)。setDefaultOptions(Boeng Trakuon);< / script> <! - 省创建下拉字段 - > < select name =sectorsclass =dropdown> < option value = 010000> Banteay Mean Chey < / option>< option value = 020000> Bat Dambang < / option>< option value = 030000> < / option>< option value = 040000> Kampong Chhnang < / option>< option value = 050000> Kampong Spueu < / option>< option value = 060000> Kampong Thum < / option>< option value = 070000> Kampot < / option>< option value = 080000> Kandal < / option>< option value = 090000> Kaoh Kong < / option>< option value = 100000> Kracheh < / option>< option value = 110000> Mondol Kiri < / option> < option value = 120000> Phnom Penh < / option>< option value = 130000> Preah Vihear < / option>< option value = 140000> Prey Veaeng < ; / option>< option value = 150000> Pousat < / option>< option value = 160000> Rotanak Kiri < / option>< op值= 170000>暹粒< / option>< option value = 180000> Krong Preah Sihanouk < / option>< option value = 190000> Stueng Traeng < / option>< option value = 210000> Takaev < / option>< option value = 220000> Otdar Mean Chey < / option>< option value = 230000> Krong Kaeb < / option>< option value = 240000 SELECTED> Krong Pailin < / option>< / select> < / td> < td> <! - 区创建下拉字段 - > < select name =districtsclass =dropdown> < script type =text / javascript> makeGeo.printOptions(districts)< / script> < / select> < / td> < td> <! - 公社创建下拉字段 - > < select name =communesclass =dropdown> < script type =text / javascript> makeGeo.printOptions(communes)< / script> < / select> < / td> < td> <! - 村庄创建下拉字段 - > < select name =villageclass =dropdown> < script type =text / javascript> makeGeo.printOptions(village)< / script> < / select> < / td> 我知道它有很多东西要看,不幸的是,非常感谢! 解决方案不幸的是,上面概述的方法将无法正常工作。当您在JavaScript段中使用php时,您必须记住,仅当从服务器请求包含javascript的文件时,才会评估PHP代码。 PHP代码在请求期间输出的任何东西(例如通过echo命令)都将成为您的JavaScript函数的一部分。在上述情况下,您没有输出任何内容,因此您的JavaScript代码将在页面加载后基本上读取 .innerHTML = \\; 。即使你在那里输出数据,也不会是动态的。 如我所见,你有3个选项: 使用AJAX从php文件加载第二个下拉列表的HTML。如果您已经熟悉AJAX,这绝对是要走的路,否则可能会有点棘手。如果您不熟悉,我一定会推荐您在尝试实施此选项之前先阅读几个教程。 当用户更改第一个下拉菜单,并使用查询字符串参数来告诉您的PHP脚本选择了哪个省份。这可能不是一个很好的选择,特别是如果这对下拉菜单是用户可能已经输入一些数据的较大形式的一部分。 将PHP输出第一个下拉列表的HTML,然后单独列出列出其各个区域的省份。 (所以如果你有10个省份,你总共会创建11个下拉列表)。然后,您将使用CSS样式 display:none; 隐藏次级下拉列表,并使用javascript将其风格切换为 display:inline-block; 。此选项对于大量选项来说并不理想,因为您正在加载大量潜在的不必要的数据。 好奇,你为什么要在用户的 $ _ SESSION 变量中存储省份数据?我通常会尝试保留用户特定的数据或与界面状态有关的信息。 I'm searching the internet now for quite some time to find a proper solution but I was not successful so far.What I try to achieve: I create a dynamic drop down box with provinces. As soon as the user selects one of the dynamic created entries, a second dynamic drop down box for districts should only display the proper entries depending on the selected province.Therefor I have build the following code:search.php//$i is running up to the max amount of provinces//for each province there shall be one option in the html select//the session array provinceresults contains key1, key2, province (english), province (other language)for($i=0; $i < $countProvinces; $i++) { echo "<option value=".$_SESSION['provincesresults'][$i][0]." onClick=\"removeSelected(\".$i.\")\">".$_SESSION['provincesresults'][$i][1]."</option>";}In the body part of the search.php I have the following JavaScript code which shall get executed when I select one of the above generated options per onClick:<!--Javascript which is needed to call the dynamic_drop_down.php function per onClick event--><script type=\"text/javascript\"> function removeUnselected($key){ document.getElementById(\"php_code\").innerHTML=\" <?php //Get all the values out of the district array out of pdo.vhd $districtsSelected = removeUnselected(".$_SESSION['provincesresults'][$key][0]."); } ?>\"; }So I need do get the $i counter out of the first PHP part into the Javascript function.After that I need the filled $districtsSelected for further use in my search.phpThe php function removeUnselected(".$_SESSION['provincesresults'][$key][0]."); looks like this and is included in the search.php:<?php/***This php file is used to retrieve the districts for a selected province.*This file is called by search.php.*As input, the function needs to be called with the ID of the selected province, it will return all related districts.*/function removeUnselected($provinceKey) { //Build the array which returns the needed districts $districtsSelected = array(); //Loop through all the districts that have been read out of the database by get_value_help.php for($i = 0; $i < count($_SESSION['districtsresults']); $i++) { //Check if the province id out of the table dbo.vhp matches with the id out of the table dbo.vhd if(strcmp($provinceKey, $_SESSION['districtsresults'][$i][1]) == 0) { //Give back the district names in english if the language settings are english if($_SESSION['lng'] == "english") { //Remove any districts that were not selected $districtsSelected[] = $_SESSION['districtsresults'][$i][2]; } //Give back the district names in khmer if the language settings are khmer elseif ($_SESSION['lng'] == "khmer") { //Remove any districts that were not selected $districtsSelected[] = $_SESSION['districtsresults'][$i][3]; } } } //Return the result return($districtsSelected);}?>Any suggestions on how I can build this in a working way are highly appreciated!Thank you and regards,codacEDIT:I am using the following JavaScript:http://www.mattkruse.com/javascript/dynamicoptionlist/index.htmlI have two problems now:As there are 24 Provinces, 86 Districts, 1600 Communes and 13500 Villages, creating for drop-down boxes takes several seconds.The tables look like this (Provinces):country_id province_id province_en province_kh000000 010000 Banteay Mean Chey Khmer 1000000 020000 Bat Dambang Khmer 2000000 030000 Kampong Cham Khmer 3000000 040000 Kampong Chhnang Khmer(districts) province_id district_id district_en district_kh 010000 010200 Mongkol Borei Khmer 1 010000 010300 Phnum Srok Khmer 2 010000 010400 Preah Netr Preah Khmer 3 010000 010500 Ou Chrov Khmer 4...same for communes and villages.I get the values out of the Microsoft SQL Server via: $sqlProvinces = "SELECT country_id, province_id, province_en, province_kh FROM dbo.vhp"; $sqlDistricts = "SELECT province_id, district_id, district_en, district_kh FROM dbo.vhd";...same for communes and villages.Like mentioned in my comment, I store these values in a $_SESSION:$_SESSION["provincesresults"]=$provincesResults;$_SESSION["districtsresults"]=$districtsResults;After that I use the function "dyndrpdwn.php" to generate the drop down list:<?phpfunction dyndrpdwn() { //count the number of provinces, districts, communes and villages for the counters of the for-statements $countProvinces = count($_SESSION["provincesresults"]); $countDistricts = count($_SESSION["districtsresults"]); $countCommunes = count($_SESSION["communesresults"]); $countVillages = count($_SESSION["villagesresults"]); //NULL the return values $returnPD = NULL; $returnC = NULL; $returnV = NULL; $defaultP = NULL; $defaultD = NULL; $defaultC = NULL; $defaultV = NULL; //Set start value for the counters to 0 $j = 0; $k = 0; $l = 0; //Start the JavaScript and create the DynamitOptionList $returnPD = "<script type=\"text/javascript\"> var makeGeo = new DynamicOptionList(\"provinces\",\"districts\",\"communes\",\"villages\");"; //Loop through all Provinces for($i = 0; $i < $countProvinces; $i++) { //Create the optionlist for provinces $returnPD = $returnPD."makeGeo.forValue(\"".$_SESSION["provincesresults"][$i][1]."\").addOptionsTextValue("; //Create the optionlist for districts ("while" if more performant than "for"!) and make sure that counter is not getting out of index while($j < $countDistricts && $_SESSION["provincesresults"][$i][1] == $_SESSION["districtsresults"][$j][0]) { $returnPD = $returnPD."\"".$_SESSION["districtsresults"][$j][2]."\",\"".$_SESSION["districtsresults"][$j][1]."\","; $returnC = $returnC."makeGeo.forValue(\"".$_SESSION["provincesresults"][$i][1]."\").forValue(\"".$_SESSION["districtsresults"][$j][1]."\").addOptionsTextValue("; //Create the optionlist for communes ("while" if more performant than "for"!) and make sure that counter is not getting out of index while($k < $countCommunes && $_SESSION["districtsresults"][$j][1] == $_SESSION["communesresults"][$k][0]) { $returnC = $returnC."\"".$_SESSION["communesresults"][$k][2]."\",\"".$_SESSION["communesresults"][$k][1]."\","; $returnV = $returnV."makeGeo.forValue(\"".$_SESSION["provincesresults"][$i][1]."\").forValue(\"".$_SESSION["districtsresults"][$j][1]."\").forValue(\"".$_SESSION["communesresults"][$k][1]."\").addOptionsTextValue("; //Create the optionlist for villages ("while" if more performant than "for"!) and make sure that counter is not getting out of index while($l < $countVillages && $_SESSION["communesresults"][$k][1] == $_SESSION["villagesresults"][$l][0]) { $returnV = $returnV."\"".$_SESSION["villagesresults"][$l][2]."\",\"".$_SESSION["villagesresults"][$l][1]."\","; //Set the Default Value $defaultV = "makeGeo.forValue(\"".$_SESSION["communesresults"][$k][1]."\").setDefaultOptions(\"".$_SESSION["searchresultspmd"][0][8]."\");"; //Increase the counter by 1 $l++; } //Cut the last "," of the string after the last value of $returnC $returnV = substr($returnV, 0, -1); //Close the JavaScript statement $returnV = $returnV.");"; //If there is no village for the commune, remove the already prepared string "makeGeo.forValue(\"".$_SESSION["provincesresults"][$i][1]."\").forValue(\"".$_SESSION["districtsresults"][$j][1]."\").forValue(\"".$_SESSION["communesresults"][$k][1]."\").addOptionsTextValue(" if(substr($returnV,-21) == "addOptionsTextValue);") { $returnV = substr($returnV, 0, -86); } //Set the Default Value $defaultC = "makeGeo.forValue(\"".$_SESSION["districtsresults"][$j][1]."\").setDefaultOptions(\"".$_SESSION["searchresultspmd"][0][7]."\");"; //Increase the counter by 1 $k++; } //Cut the last "," of the string after the last value of $returnC $returnC = substr($returnC, 0, -1); //Close the JavaScript statement $returnC = $returnC.");"; //If there is no commune for the district, remove the already prepared string "makeGeo.forValue(\"".$_SESSION["provincesresults"][$i][1]."\").forValue(\"".$_SESSION["districtsresults"][$j][1]."\").addOptionsTextValue(" if(substr($returnC,-21) == "addOptionsTextValue);") { $returnC = substr($returnC, 0, -66); } //Set the Default Value $defaultD = "makeGeo.forValue(\"".$_SESSION["provincesresults"][$i][1]."\").setDefaultOptions(\"".$_SESSION["searchresultspmd"][0][8]."\");"; //Increase the counter by 1 $j++; } //Cut the last "," of the string after the last value of $returnPD $returnPD = substr($returnPD, 0, -1); //Close the JavaScript statement $returnPD = $returnPD.");"; //If there is no district for the province, remove the already prepared string "makeGeo.forValue(\"".$_SESSION["provincesresults"][$i][1]."\").addOptionsTextValue(" if(substr($returnPD,-21) == "addOptionsTextValue);") { $returnPD = substr($returnPD, 0, -47); } //Set the Default Value $defaultP = "makeGeo.forValue(\"provinces\").setDefaultOptions(\"".$_SESSION["provincesresults"][$i][1]."\");"; } //Put Provinces, Districts, Communes and Villages together and close the Javascript $returnPDCV = $returnPD.$returnC.$returnV.$defaultD.$defaultC.$defaultV."</script>"; //Return the result return sprintf($returnPDCV);}?>In order to use the JavaScript, I use the following code in the patient_update.php://include the dynamic drop down generatorinclude("/functions/dyndrpdwn.php");<!--Adding JavaScript for dynamic dropdown list--><script type=\"text/javascript\" src=\"/js/dynamicoptionlist.js\"></script>//Call the dynamic drop down functionecho dyndrpdwn();echo"<!--Province Create Drop-Down Field--> <select name=\"provinces\" class =\"dropdown\">";//Fill the drop down, when data is received by get_value_help.php or if session array is already filledif(isset($_GET["value"]) == "true" && $_GET["value"] == "receive" || isset($_SESSION["provincesresults"]) == "true" && count($_SESSION["provincesresults"]) > 0) { //Get all the values out of the Province array out of pdo.vhd$countProvinces = count($_SESSION["provincesresults"]); for($i=0; $i < $countProvinces; $i++) { //Display the Khmer or the English language depending on the website settings. $_SESSION["searchresultspmd"][0][5]) = province_id in dbo.pmd //$_SESSION["provincesresults"][$i][1] = province_id in dbo.vhp if(isset($_SESSION["lng"]) == "true") { switch ($_SESSION["lng"]) { case "english": if($_SESSION["provincesresults"][$i][2] == $_SESSION["searchresultspmd"][0][5]) { echo"<option value=".$_SESSION["provincesresults"][$i][1]." SELECTED>"; } else { echo"<option value=".$_SESSION["provincesresults"][$i][1].">"; } echo"".$_SESSION["provincesresults"][$i][2]." </option>"; break; case "khmer": if($_SESSION["provincesresults"][$i][2] == $_SESSION["searchresultspmd"][0][5]) { echo"<option value=".$_SESSION["provincesresults"][$i][1]." SELECTED>"; } else { echo"<option value=".$_SESSION["provincesresults"][$i][1].">"; } echo"".$_SESSION["provincesresults"][$i][3]." </option>"; break; } } }}echo" </select> </td> <td> <!--District Create Drop-Down Field--> <select name=\"districts\" class =\"dropdown\"> <script type=\"text/javascript\"> makeGeo.printOptions(\"districts\") </script> </select> </td> <td> <!--Commune Create Drop-Down Field--> <select name=\"communes\" class =\"dropdown\"> <script type=\"text/javascript\"> makeGeo.printOptions(\"communes\") </script> </select> </td> <td> <!--Village Create Drop-Down Field--> <select name=\"villages\" class =\"dropdown\"> <script type=\"text/javascript\"> makeGeo.printOptions(\"villages\") </script> </select> </td>...So there are two questions now:Calling the dyndrpdwn.php function takes quite a few seconds, as there are ~24 Provinces, ~86 Districts, ~1600 Communes and ~13500 Villages and I loop through them. Is there any way how to improve the performance?With setDefaultOptions I try to set the Default Value for the proper drop-down list. But in my code it does not work. I've compared it with the examples on [the JavaScript website][1] but I couldn't find the error... Can you see why it is not working the way I do it?The result looks currently like that:<script type="text/javascript">var makeGeo = new DynamicOptionList("provinces","districts","communes","villages");This creates the entries for provinces and districts:makeGeo.forValue("010000").addOptionsTextValue("Mongkol Borei","010200","Phnum Srok","010300","Preah Netr Preah","010400","Ou Chrov","010500","Serei Saophoan","010600","Thma Puok","010700","Svay Chek","010800","Malai","010900");This creates the entries for the communesmakeGeo.forValue("010000").forValue("010200").addOptionsTextValue("Banteay Neang","010201","Bat Trang","010202","Chamnaom","010203","Kouk Ballangk","010204","Koy Maeng","010205","Ou Prasat","010206","Phnum Touch","010207","Rohat Tuek","010208","Ruessei Kraok","010209","Sambuor","010210","Soea","010211","Srah Reang","010212","Ta Lam","010213");This creates the entries for the villages:makeGeo.forValue("010000").forValue("010200").forValue("010201").addOptionsTextValue("Ou Thum","01020101","Phnum","01020102","Banteay Neang","01020103","Kouk Pnov","01020104","Trang","01020105","Pongro","01020106","Kouk Tonloab","01020107","Trabaek","01020108","Khile","01020109","Samraong Pen","01020110","Dang Run Lech","01020111","Dang Run Kaeut","01020112","Ou Snguot","01020113","Prey Changha Lech","01020114","Prey Changha Kaeut","01020115","Ou Andoung Lech","01020116","Ou Andoung Kandal","01020117","Ou Andoung Kaeut","01020118","Kouk Kduoch","01020119");And this should set the default value for the province, district and commune (just 3 examples; they don't work so far...):makeGeo.forValue("240000").setDefaultOptions("Boeng Trakuon");makeGeo.forValue("240200").setDefaultOptions("Ou Andoung");makeGeo.forValue("240204").setDefaultOptions("Boeng Trakuon");</script><!--Province Create Drop-Down Field--><select name="provinces" class ="dropdown"> <option value=010000>Banteay Mean Chey </option><option value=020000>Bat Dambang </option><option value=030000>Kampong Cham </option><option value=040000>Kampong Chhnang </option><option value=050000>Kampong Spueu </option><option value=060000>Kampong Thum </option><option value=070000>Kampot </option><option value=080000>Kandal </option><option value=090000>Kaoh Kong </option><option value=100000>Kracheh </option><option value=110000>Mondol Kiri </option><option value=120000>Phnom Penh </option><option value=130000>Preah Vihear </option><option value=140000>Prey Veaeng </option><option value=150000>Pousat </option><option value=160000>Rotanak Kiri </option><option value=170000>Siem Reab </option><option value=180000>Krong Preah Sihanouk </option><option value=190000>Stueng Traeng </option><option value=200000>Svay Rieng </option><option value=210000>Takaev </option><option value=220000>Otdar Mean Chey </option><option value=230000>Krong Kaeb </option><option value=240000 SELECTED>Krong Pailin </option></select> </td> <td> <!--District Create Drop-Down Field--> <select name="districts" class ="dropdown"> <script type="text/javascript"> makeGeo.printOptions("districts") </script> </select> </td> <td> <!--Commune Create Drop-Down Field--> <select name="communes" class ="dropdown"> <script type="text/javascript"> makeGeo.printOptions("communes") </script> </select> </td> <td> <!--Village Create Drop-Down Field--> <select name="villages" class ="dropdown"> <script type="text/javascript"> makeGeo.printOptions("villages") </script> </select> </td>I know its quite a lot of stuff to look through, sorry for that butevery help is highly appreciated! 解决方案 Unfortunately, the approach you outline above will not work. When you use php inside a javascript segment, you have to remember that the php code will be evaluated when the file containing the javascript is requested from the server only. Anything the PHP code has output during the request (e.g. via an 'echo' command) will then become part of your javascript function. In the case above, you have not output anything so your javascript code will essentially read .innerHTML=\" \"; once the page loads. Even if you did output data there, it would not be dynamic.As I see it, you have 3 options:Use AJAX to load the HTML for the second drop down from a php file. This is definitely the way to go if you are already familiar with AJAX, but could be a bit tricky otherwise. If you aren't familiar, I would definitely recommend going through a few tutorials before trying to implement this option.Reload the page when the user changes the first drop down, and use a query string parameter to tell your PHP script what province has been selected. This is probably not a very good option, especially if this pair of drop downs is part of a larger form that the user might have already entered some data into.Have your PHP output the HTML for the first drop down, and then a separate drop down for each province that lists its respective districts. (So if you have 10 provinces, you would create 11 drop downs total.) Then you would use the CSS style display: none; to hide the secondary drop downs and use javascript to toggle their style to display: inline-block;. This option is not ideal for large numbers of options, because you are loading tons of potentially unnecessary data.Out of curiosity, why are you storing the province data in the user's $_SESSION variable? I typically try to reserve that for user specific data or information pertaining to the state of the interface. 这篇关于创建动态下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-12 10:42