How to load second DropDown list from Database aft

2019-02-21 01:08发布

问题:

I am building a Web App. At some point a user needs to input data to a form. This form has several text fields and DropDownLists.

One of the DDLs is dependent on its previous DDL. What happens is that when the user selects a value from the first DDL, the second DDL should load data from the database that are related to the selected value of the first DDL.

Up to this point I've implemented only PHP and JS, ( no AJAX, jQuery or anything else ) for handling most of my problems.

I'd like to know how to populate the 2nd DDL from the database after an item on the first DDL was selected.

Any help would be appreciated. Thank you!

回答1:

Ajax is your best bet. this will help



回答2:

Here's an example:

http://tutorialzine.com/2011/11/chained-ajax-selects-jquery/

Google is your friend :)



回答3:

If the data in the second drop-down is dependent on the data in the first, then you will have to load the values of the second dropdown into a javascript object, like so:

// Given the options in the first dropdown are: "foo", "bar", and "baz"
var secondData = {
    foo: ['lorem', 'ipsum'],
    bar: [1,2,3],
    baz: []
}

Add a 'change' event to the first dropdown, and given the value of that dropdown, load the contents of the second dropdown with the values contained in the secondData object.



回答4:

If you're comfortable using jQuery (which I would highly recommend), something like this should do:

$("#dropdown").on("change", function() {//change [dropdown] to the actual ID of your dropdown
    var selected=$(this).find("option:selected").val();//assuming your dropdown has a value to send, otherwise use text()

    $.get("options.php?selected="+selected, function(data) {
        var options=data.split("\n");
        var newSelectHTML="<select name=\"whatever\">\n";

        for (var i=0;i<options.length;i++) {
            newSelectHTML+="<option>"+options[i]+"</option>";
        }

        newSelectHTML+="</select>";
        $("#form").append(newSelectHTML);//again, change [form] to the correct ID.
    }
}

This code simply gets the value of the currently selected option of the DDL with the ID "dropdown" (change as necessary) and sends it to PHP file options.php in $_GET["selected"];. Assuming that file then outputs a list of options separated by a new line (\n). The JavaScript then takes that, splits it by line, loops through the options, and creates the HTML for a new DDL and appends that to element ID form. No error handling is there, but that, as they say, is an exercise for the reader. Whatever is returned is in the variable data.