简体   繁体   English

如何“链接”两个下拉列表与php,javascript,mysql?

[英]how to “link” two drop-down lists with php, javascript, mysql?

I want to create a form with two drop-down lists (country and town), filled with options from two mysql tables. 我想创建一个带有两个下拉列表(国家和城镇)的表单,其中填充了来自两个mysql表的选项。 And I would like the second list (towns) to be populated with options depending on the value of selected option on the first list (country). 我希望第二个列表(城镇)中填充选项,具体取决于第一个列表(国家/地区)上所选选项的值。

I know how to load the options with php and mysql into the countries list and I can link this to a second list that is populated with options from a javascript. 我知道如何将php和mysql的选项加载到国家列表中,并且我可以将其链接到第二个列表,该列表中填充了来自javascript的选项。 There are conditionals in the script that updates the values of the second list. 脚本中有条件更新第二个列表的值。 But I need some help with the mysql query for the second list. 但是我需要有关第二个列表的mysql查询的帮助。 How can I start a second query when the page is already loaded? 页面已加载后,如何启动第二个查询?

You've got two general ways of going about this. 您有两种一般的解决方法。

First, is to include all of the values into the page possibly as a javascript array, then as the first list is changed, it just re-adds the appropriate values to the second drop-down. 首先,是将所有值都可能以javascript数组的形式包含在页面中,然后在更改第一个列表时,只需将适当的值重新添加到第二个下拉列表中即可。 If you use this method, every item (from both tables/lists) is loaded on every request. 如果使用此方法,则会在每个请求中加载(来自两个表/列表的)每个项目。 If the total number of items is relatively small (say <100) then probably your best approach. 如果项目总数相对较小(例如<100),则可能是最好的方法。

The other option is to issue an ajax request after the first dropdown is selected. 另一个选项是在选择第一个下拉列表后发出ajax请求。 The request would contain the id/value of the dropdown, and would return the items that are valid for that value. 该请求将包含下拉列表的ID /值,并将返回对该值有效的项目。 This method means you only need one query on the initial page load (the values for the first dropdown) but also requires you to create a javascript handler. 此方法意味着您只需要在初始页面加载时查询(第一个下拉列表的值),还需要创建一个javascript处理程序。

I've seen both approaches used. 我已经看到两种方法都使用过。 The first one is usually better for smaller datasets, but can be faster since the query is static (no parameters), and can be cached. 第一个通常对较小的数据集更好,但是由于查询是静态的(无参数)并且可以被缓存,因此可以更快。 However, you then transmit that data on every request. 但是,然后在每个请求上传输该数据。 The second one is slightly "cleaner" but requires at least one ajax request. 第二个稍微“干净”,但是至少需要一个ajax请求。 If you are already familiar with using that approach then probably your best option. 如果您已经熟悉使用该方法,那么可能是您的最佳选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM