当在第一个下拉列表中选择一个值时,过滤第二个下拉列表

时间:2015-02-05 作者:user3515709

我有一张有两个下拉列表的表。第一个是品牌,这是WordPress定制的帖子类型。第二种是口味,也是一种自定义的帖子类型。品牌是口味之母。当我选择一个品牌时,我需要用这个品牌(儿童)的口味更新第二个下拉列表。

我为我的列表创建了短代码,并正确填写了它们。但当第一个下拉列表发生变化时,我不知道如何过滤第二个下拉列表。

这是我的桌子:

 <table id="fla_inf" width="100%">
<tbody>
<tr>
<th class="tab_header" colspan="6">Flavors and Additives</th>
</tr>
<tr>
<th class="tab_header_nam">Flavor Brand</th>
<th class="tab_header_nam">Flavor Name</th>
<th class="tab_header_nam">Dropper type</th>
<th class="tab_header_nam">Quantity Unit</th>
<th class="tab_header_nam">Quantity</th>
<th class="tab_header_nam">Add/Remove row</th>
</tr>
<tr class="flavors">
<td>[brand_list]</td>
<td>[flavor_list]</td>
<td><select id="dropper0" class="dropper">
<option selected="selected" value="type1">type 1</option>
<option value="type2">type 2-3</option>
</select></td>
<td><select id="qtyunit0" class="qtyunit">
<option value="ml">ml</option>
<option value="drops">drops</option>
<option selected="selected" value="perc">%</option>
</select></td>
<td><input id="quantity0" class="quantity" type="number" /></td>
<td><input class="addline" src="http://spitilab.com/wp-content/uploads/2015/01/add.png" type="image" /><input class="remline" src="http://spitilab.com/wp-content/uploads/2015/01/delete.png" type="image" /></td>
</tr>
</tbody>
</table>
以下是我的短代码:

function GetBrandList() {

    $brands = wp_dropdown_pages(array(\'id\'=>\'marque0\',\'post_type\' => \'marque-type\',\'echo\'=>0));
    return $brands;
} 

function GetFlavorList() {

   $flavors = wp_dropdown_pages(array(\'id\'=>\'arome0\',\'post_type\'=>\'aromes-type\',\'echo\'=>0));
   return $flavors;
}   

add_shortcode(\'brand_list\', \'GetBrandList\');
add_shortcode(\'flavor_list\', \'GetFlavorList\');
以下是我的更新:

我在函数中添加了以下内容。php

 add_action( \'wp_ajax_brand_children\', \'GetBrandChildren\');
add_action( \'wp_ajax_nopriv_brand_children\', \'GetBrandChildren\');

function GetBrandChildren($parent_id,$id) {
   $children = wp_dropdown_pages(array(\'id\'=>\'arome$id\',\'post_type\'=>\'aromes-type\',\'child_of\'=>$parent_id,\'echo\'=>0));
   return $children;
}
下面是我的jquery:

    //On selected brand, update flavors list
$(document).on(\'change\', "select[id^=\'marque\']", function() {

        var $brandid =  $(this).val();
        var $brand_dd_id = $(this).attr(\'id\');
        var $flav_dd_id = $brand_dd_id.substr($brand_dd_id.length-1);
        $("#arome"+$flav_dd_id).empty();

        //Make AJAX request, using the selected value as the GET
        $.ajax({data: \'{"parent_id":"\' + $brandid + \'","id":"\'+ $flav_dd_id +\'","action":"brand_children"}\',
                success: function(output) {
                    alert(output);
                    $("#arome"+$flav_dd_id).html(output);
                }
         });

});
然而,我的口味下拉列表仍然是空的。在警报中显示的输出中,似乎返回了完整的html页面。

更新时间:

add_action( \'wp_ajax_brand_children\', \'GetBrandChildren\');
add_action( \'wp_ajax_nopriv_brand_children\', \'GetBrandChildren\');

function GetBrandChildren() {
   $parent_id = $_POST[\'brandid\'];
   $id = $_POST[\'flav_dd_id\'];
   echo wp_dropdown_pages(array("id"=>"arome$id",\'post_type\'=>\'aromes-type\',\'child_of\'=>$parent_id,\'echo\'=>0));
  //ob_clean();
  //echo "working";
  wp_die();
}

// need these two lines to be ale to locate the admin-ajax.php inside jquery
wp_enqueue_script( \'my-ajax-request\', get_template_directory_uri() . \'/js/ajax.js\', array( \'jquery\' ) );
wp_localize_script( \'my-ajax-request\', \'MyAjax\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) );
JQuery:

//On selected brand, update flavors list
$(document).on(\'change\', "select[id^=\'marque\']", function() {

        var $brandid =  $(this).val();
        var $brand_dd_id = $(this).attr(\'id\');
        var $flav_dd_id = $brand_dd_id.substr($brand_dd_id.length-1);
        $("#arome"+$flav_dd_id).empty();

        //Make AJAX request, using the selected value as the GET
        //var ajax_url = admin_url(\'admin-ajax.php\');
        $.ajax({
                url: MyAjax.ajaxurl,
                data: {
                        \'parent_id\': $brandid,
                        \'id\': $flav_dd_id,
                        \'action\': \'brand_children\'
                      },
                success: function(output) {
                    console.log(output);
                    $("#arome"+$flav_dd_id).html(output);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status + " "+ thrownError);
        }});

});
现在,我的第二个下拉列表已更新。

1 个回复
最合适的回答,由SO网友:OnethingSimple 整理而成

您需要使用Ajax来完成此操作,以便在选择第一个下拉列表后加载第二个下拉列表。我不确定你在上面做的几件事,所以我只想给你编个代码,你可能需要在这里或那里更改一些东西,我会尽可能地完成它。因此,首先要做的是设置一个ajax操作。理想情况下,这应该在插件中设置。之所以使用is\\u admin(),是因为当从包含下拉列表的页面发送Ajax请求时,它将在admin下运行。如果感觉我们在倒退,那只是一个鸡蛋的问题。哪个先到,请求还是处理程序。。。粗糙的处理者,这就是为什么我从这里开始。

<?php
if ( is_admin() ) {
    // We add 2 actions, the first is for logged in users, the second for guests.
    add_action( \'wp_ajax_dynamic_dropdown\', \'dynamic_dropdown_func\' );
    add_action( \'wp_ajax_nopriv_dynamic_dropdown\', \'dynamic_dropdown_func\' );
}

// This is the function that will handle your Ajax Request/Response
function dynamic_dropdown_func () {
    global $wpdb;
    if (isset($_POST[\'value\'])) {
        $selected_option = $_POST[\'value\'];
        // This will be your second dropdown here, this will be returned in an Ajax request
        $args = array(
            \'show_option_none\' => __( \'Pick Another One\' ),
            \'class\' => \'dropper\',
            \'id\' => \'dropper0\',
            \'orderby\' => \'ID\',
            \'order\' => \'ASC\',
            \'hide_empty\' => 0,
            \'hierarchical\' => 1,
            \'depth\' => 1,
            // This is what will get us the children of first selected option
            \'child_of\' => (int)$selected_option,
            \'echo\' => 0,
            // Make sure you switch out this const for your tax
            \'taxonomy\' => MY_CUSTOM_TAX,
        );

        $my_second_dropdown = wp_dropdown_categories( $args );
        // If you want to do any preg_replace or str_replace, do it here before we do the ob_clean() below         
    }
    //ob_clean is to prevent errors, echos, anything that has outputted to this point in the Ajax WP instance that could ruin your return.
    ob_clean();
    return $my_second_dropdown;
    wp_die();
}
好的,现在我们要做代码的前端部分。这是用户将看到的部分。当它们触发Ajax请求时,应在响应时加载第二个下拉列表。通常,您将使用ajax\\u url的变量和我们需要在JS中使用的任何其他PHP值来本地化JavaScript文件,以便向WP发送ajax请求。我们将进行一些作弊,只需将脚本打印到页面上,我们就会得到相同的结果。只需确保理想情况下在正文末尾打印此脚本,否则必须添加一个文档就绪函数,无论如何都不会有任何影响。

function my_frontend_javascript () {
    $ajax_url = admin_url( \'admin-ajax.php\' );
    $javascript = "
        <script>
            var ajaxUrl = {$ajax_url},
            // Now lets grab our dropdowns
                dropdownArome   = jQuery(\'#arome0\'),
                dropdownDropper = jQuery(\'#dropper0\');

            if (dropdownArome.length && dropdownDropper.length) {
                // Good, our elements exist
                dropdownArome.on(\'change\', function (e) {
                    var value = e.target.selectedOptions[0].value,
                        success,
                        data;
                    if (!!value) {
                        // Alright, lets send that value to our Ajax Script, note that the action is the same as the Ajax action hook we used earlier
                        data = {
                            \'my_value\' : value,
                            \'action\'   : \'dynamic_dropdown\'
                        };
                        success = function ( response ) {
                            // This response will hold our <option>\'s
                            dropdownDropper.html( response );
                        };
                        jQuery.post( ajaxUrl, data, success );
                    }
                });
            }
        </script>";
    return $javascript;
}

/** This is where we build our site/form/dropdowns */

$args = array(
    \'show_option_none\' => __( \'Pick One\' ),
    \'class\' => \'arome\',
    \'id\' => \'arome0"\',
    \'orderby\' => \'ID\',
    \'order\' => \'ASC\',
    \'hide_empty\' => 0,
    \'hierarchical\' => 1,
    \'depth\' => 1,
    \'echo\' => 0,
    // Make sure you switch out this const
    \'taxonomy\' => MY_CUSTOM_TAX,
);

$my_first_dropdown = wp_dropdown_categories( $args );

// Alright, so now we print out the 2 dropdowns, then the JavaScript from function we wrote above
echo $my_first_dropdown;
echo \'<br /><div id="dropper0-container"></div><br />\';
echo my_frontend_javascript();

/** That Should be it! Like I said, you will have to tweak some options to fit your site and your implementation. */
所以这就是你将如何做你正试图做的事情,我想这可能是最简单的方法之一。我说最简单是因为我们实际上没有进行验证,现在,我们几乎假设一切都很顺利。我建议您在WP中阅读Ajax,即使您知道一些,了解更多也无妨。我希望通过一些调整,这段代码可以很好地为您服务。

http://codex.wordpress.org/AJAX_in_Plugins

http://www.smashingmagazine.com/2011/10/18/how-to-use-ajax-in-wordpress/

结束

相关推荐

WP_DROPDOWN_ROLES()替换选项值=CODE

我正在尝试替换插件中角色的硬编码下拉列表。目前代码如下:echo \'<select name=\"xf_user_role_\' . $id . \'\" id=\"xf_user_role_\' . $id . \'\">\'; ?> <option value=\'subscriber\' <?php echo ($xf_options[\'xf_user_role\'][$id] == \'subscriber\') ? \"sele