是否可以使用值作为参数使用dropdown onchange重定向?

时间:2015-02-11 23:09:35

标签: php redirect yii2

使用Yii2我有以下代码,显示我的类别列表的下拉列表。

我想知道是否有可能在更改时执行的操作是localhost:8888 / article / category?id = 1而不是它是什么(localhost:8888 / article / category)。

这需要AJAX和/或JS还是只能用php完成?(id更喜欢php)

<?php $form = ActiveForm::begin(['id' => 'category-form', 'action' =>   
'/advanced/article/category',]); ?>

 <?= $form->field($model, 'category')->dropDownList($model->categoryList,[

'prompt'=>'Select Category to view',
'onchange'=>'this.form.submit()'

]) ?>

<?php ActiveForm::end(); ?>

3 个答案:

答案 0 :(得分:2)

你不需要ajax。 js会这样做。

<?= $form->field($model, 'category')->dropDownList($model->categoryList,[
                                'prompt'=>'Select Category to view',
                                'id'=>'cat-id',
                            ]) ?>

js在选中时重定向

$this->registerJs( 
'$(document).ready(function(){ 
$("#cat-id").change(function(){
var e = document.getElementById("cai-id");
    var strSel =  e.options[e.selectedIndex].value;
    window.location.href="'.Yii::$app->urlManager->createUrl('category?id=').'" + strSel;
});

});', View::POS_READY); 

答案 1 :(得分:2)

如果您想在不编写任何其他javascript的情况下使用onchange属性,则需要更正一些代码以使其正常工作。

1)将您的表单method更改为get(默认情况下为post):

<?php $form = ActiveForm::begin([
    'id' => 'category-form',
    'action' => '/advanced/article/category',
    'method' => 'get', // Add this to your code
]); ?>

2)dropDownList选项中明确设置类别字段的名称,以避免包含formName()

<?= $form->field($model, 'category')->dropDownList($model->categoryList, [
    'prompt'=>'Select Category to view',
    'onchange'=>'this.form.submit()',
    'name' => 'category', // Add this to your code
]) ?>

答案 2 :(得分:-1)

抱歉,您可以制作一个onchange示例,但这次是使用yii2中的radiolist

field($ model,'estadoLaboral') - &gt; radioList(array('T'=&gt;'Actualmentetrabajoaquí','B'=&gt;'Ya notrabajoaquí'))?&gt; 使用javascript