【发布时间】:2018-01-22 12:47:51
【问题描述】:
我在 Yii2 中有一个单页应用程序
主页包含 1.带有对象列表的列+创建按钮 2. 创建/更新表单的动态内容栏
我的问题是在加载(通过 ajax)创建表单时,然后我通过 AjaxSubmitButton 发送数据,这很好(数据库更新),但不是用新对象数据更改动态内容区域,而是重定向到视图部分表格。
我怎样才能使新响应进入发送它的同一个 div?
这是现在在#singleObjContainer 中加载的表单
<div class="course-form">
<?php
$form = yii\bootstrap\ActiveForm::begin();
?>
<span>
<h4 class='listTitle'>Add Course</h4>
</span>
<span class="form-group pull-right">
<?php
AjaxSubmitButton::begin([
'label' => 'Save',
'ajaxOptions' => [
'type'=>'POST',
'url'=> Url::toRoute(['course/create-form']),
'success' => new \yii\web\JsExpression('function(html)
{
$("#singleObjContainer").empty().append(html);
}'),
],
'options' => ['class' => 'btn btn-success', 'type' => 'submit'],
]);
AjaxSubmitButton::end();
?>
</span>
<hr class='myHr'>
<div>
<?php
echo $form->field($model, 'name')->textInput(['maxlength' => true]);
echo $form->field($model, 'description')->textarea(['rows' => '4']);
echo $form->field($model, 'img')->label(Html::img(Yii::getAlias('@uploadsUrl/').'courses/'.$model->img,['width' => '30%']),['encodeLabel' => false])->fileInput();
?>
</div>
<?php ActiveForm::end(); ?>
这是控制器动作:
public function actionCreateForm()
{
$model = new Course();
if ( $model->load(Yii::$app->request->post()))
{
// get the instance of the image
$image = UploadedFile::getInstance( $model, 'img');
// save image name to the model
$model->img = $image->baseName.".".$image->extension;
// go through validation rule and save
if( $model->save() )
{
// validation ok, save image in the file system
$image->saveAs( Yii::getAlias('@uploads/').'courses/'.$model->img);
// load the details view into the singleObj container
$courseStudents = $this->getCourseStudents($model['id']);
return $this->renderPartial('_viewForm', ['model' => $model, 'courseStudents' => $courseStudents]);
}
}
else
{
return $this->renderPartial('_createForm', ['model' => $model,]);
}
}
【问题讨论】:
-
而不是使用
renderPartial使用renderAjax
标签: ajax yii2 single-page-application renderpartial