开发者

how to "link" two drop-down lists with php, javascript, mysql?

开发者 https://www.devze.com 2023-01-24 23:20 出处:网络
I want to create a form with two drop-down lists (country and town), filled with options from two mysql tables. And I would like the second list (towns) to be populated with options depending on the v

I want to create a form with two drop-down lists (country and town), filled with options from two mysql tables. 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. 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. How can I start a second query when the page开发者_Python百科 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. 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.

The other option is to issue an ajax request after the first dropdown is selected. The request would contain the id/value of the dropdown, and would return the items that are valid for that value. 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.

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. If you are already familiar with using that approach then probably your best option.

0

精彩评论

暂无评论...
验证码 换一张
取 消