我是 yii2 的新手。当我单击按钮时,jquery 触发向 Controller 发送 ajax 请求的事件。代码如下:
$("#save").on('click', function() {
var data = 'test';
$.ajax({
url: 'index.php?r=site%2Fcreate-mockup',
type: 'POST',
data: {dat: data},
success: function(data) {
console.log(data);
}
});
});
在 Controller 中创建 Mockup 类的实例
public function actionCreateMockup()
{
if (Yii::$app->request->isAjax)
{
$create_model = new Mockup();
//filling $create_model
return $this->redirect(Url::to(['site/saved-mockups']));
}
}
当我删除 $create_model = new Mockup(); 时//填充$create_model,然后就可以了。 样机.php:
<?php
namespace app\models;
use yii\base\Model;
use yii\db\ActiveRecord;
class Mockup extends ActiveRecord
{
}
?>
最佳答案
由于您使用 ajax 提交表单并期望在 ajax success
回调中返回响应,因此您可以继续使用 JavaScript 来处理其余场景,并在提交数据后重定向用户已保存。
这里有一些可以让你继续前进的东西
$("#save").on('click', function() {
var data = 'test';
$.ajax({
url: 'index.php?r=site%2Fcreate-mockup',
type: 'POST',
data: {dat: data},
dataType: 'JSON',
success: function(response) {
if(response.success){
window.location = response.route //redirect on success
}else{
//handle errors here
}
}
});
});
比在你的 Controller 中
public function actionCreateMockup()
{
if (Yii::$app->request->isAjax)
{
$create_model = new Mockup();
//filling $create_model
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
if($create_model->load(\Yii::$app->getRequest()->post()) && $create_model->save()){
return [
'success'=> true,
'route'=> Url::to(['site/saved-mockups'])
];
}else{
return [
'success'=> false,
'errors'=> $create_model->getErrros();
];
}
}
}
关于javascript - yii2 不起作用 $this->redirect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47293585/