簡體   English   中英

yii2不起作用$ this-> redirect

[英]yii2 doesn't work $this->redirect

我是yii2的新手。 當我單擊按鈕時,jquery觸發將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);
            }
        });
    });

在控制器中創建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,然后開始工作。 Mockup.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
            }
        }
    });
});

比你的控制器

    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();
            ];
        }
       }
     }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM