php下拉菜单填充

2021-12-28 00:00:00 drop-down-menu jquery php

我正在尝试编写一个 php 脚本,该脚本将根据主下拉菜单的选择来填充第二个下拉菜单.我想用 jquery 来做所有非页面刷新的事情.但是我发现存在的每一件事都很难理解和修改,你知道任何写得很好且易于理解的东西,或者可能存在的教程吗?

I'm trying to write a php script that will populate a second drop down menu based on the selection of the a primary drop down menu. I would like to use jquery to do all the non-page refresh stuff. but every thing that I find that exists out there is hard to understand and modify, do you know of anything that was well written and easy to understand or maybe a tutorial that exists out there?

推荐答案

以下是一些代码,可以让您了解您想要做什么:

Here's some code that should give you an idea of what you want to do:

HTML

<select id="state" name="state">
    <option value="IL">Illinois</option>
    <option value="IN">Indiana</option>
</select>
<select id="city" name="city">
    <option value="">Please select a state...</option>
</select>

PHP

<?php
    $cities = array(
        'IL' => array( 'Chicago', 'Naperville', 'Decatur', 'Saint Charles' ),
        'IN' => array( 'Gary', 'Miller', 'Portage', 'Merrillville' )
    );

    print json_encode( $cities[ $_POST[ 'state' ] ] );
    exit;
?>

jQuery

jQuery(document).ready(function() {

    jQuery('#state').change(function() {
        jQuery.post(
            'some-url.php',
            {
                'state':jQuery('#state').val()
            },
            function(data, textStatus) {
                jQuery.each(data, function(index, value) {
                    jQuery('#city').append('<option value="' + value + '">' + value + '</option>');
                });
            },
            'json'
        );
    });

});

相关文章