多级依赖下拉列表是指当一个下拉列表的选择会动态影响另一个下拉列表内容的交互方式。在Yii框架中使用AJAX实现这种功能是常见的需求。
// 在视图文件中
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\web\JsExpression;
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'parent_id')->dropDownList(
$parentItems,
[
'prompt' => '请选择...',
'id' => 'parent-id',
'onchange' => new JsExpression('
$.ajax({
url: "' . Url::to(['controller/get-child']) . '",
type: "POST",
data: {parent_id: $(this).val()},
success: function(data) {
$("#child-id").html(data.options);
$("#child-id").prop("disabled", false);
},
error: function() {
alert("请求失败");
}
});
')
]
) ?>
<?= $form->field($model, 'child_id')->dropDownList(
[],
[
'prompt' => '请先选择父级...',
'id' => 'child-id',
'disabled' => true
]
) ?>
<?php ActiveForm::end(); ?>
public function actionGetChild()
{
if (Yii::$app->request->isAjax) {
$parentId = Yii::$app->request->post('parent_id');
$childItems = ChildModel::find()
->where(['parent_id' => $parentId])
->all();
$options = '<option value="">请选择...</option>';
foreach ($childItems as $item) {
$options .= '<option value="'.$item->id.'">'.$item->name.'</option>';
}
return $this->asJson([
'options' => $options
]);
}
throw new \yii\web\BadRequestHttpException('非法请求');
}
在AJAX请求中添加CSRF令牌:
data: {
parent_id: $(this).val(),
_csrf: yii.getCsrfToken()
},
确保控制器返回的是JSON格式数据:
return $this->asJson(['options' => $options]);
确保Url::to()生成的URL正确,可以在浏览器中直接访问测试
use yii\widgets\Pjax;
Pjax::begin(['id' => 'child-list']);
echo $form->field($model, 'child_id')->dropDownList(
$childItems,
['prompt' => '请选择...']
);
Pjax::end();
$this->registerJs('
$("#parent-id").change(function() {
$.pjax.reload({
url: "'.Url::to(['controller/get-child']).'?parent_id=" + $(this).val(),
container: "#child-list",
timeout: 5000
});
});
');
通过以上方法,应该能够解决Yii框架中AJAX多级下拉列表不工作的问题。如果仍有问题,建议检查浏览器控制台错误信息和网络请求响应。
没有搜到相关的文章