双下拉列表值

I am thinking about two drop down list, one is depended on another. Both drop down list have values from database. In this case which one is the best way.

  1. Retrieve all values from database using plain PHP then store them in javascript variable, later search for second drop down list value (if first drop down list's value changes)in the javascript (array) variable.

  2. If first drop down list's value changes then retrieve values for second drop down list from database using AJAX(jQuery).

It depends on many things.

You must have to show first dropdown by fetching data from database,

if data for each selected record from dropdown one is big then get it using ajax else make js variables and populate it using javascript on select of first dropdown.

As per your criteria it will be best for your to go with the Ajax late loading, that will make your page load fast while loading and you can get data for other dropdown using ajax.

The two alternatives that you've indicated has pros and cons, the decision depends on how this pros and cons affects your application:

Retrieve all values from database using plain PHP then store them in javascript variable, later search for second drop down list value (if first drop down list's value changes)in the javascript (array) variable.

Pros:

  • Minimizes the http petitions, you only need one petition to retrieve the whole data.
  • Minimizes the query's needed against the database, generally you only perform one query.

Cons:

  • Increases the amount of memory used if you have big amounts of data.
  • If your data changes constantly, your visitors don't see the changes until it refresh the whole page.

If first drop down list's value changes then retrieve values for second drop down list from database using AJAX(jQuery).

Pros:

  • You don't need to store all the whole data in memory, only the data that will be used, reducing the amount of memory needed.
  • Your data is updated every time without the need of reload the page, only changing the selection.

Cons:

  • You need to perform several http petitions and runs querys against the database every time the selection changes.

Personally I prefer method 2 if the amount of data is relatively big and the performance is not a must.