如何在没有刷新Yii页面的情况下显示javascript警报?

时间:2018-05-13 00:17:00

标签: javascript yii2 alert

我有以下代码,以避免在我的桌子上重复产品名称。但是,当我接受警报对话框时,它会将我发送到空白页面。

/**
 * Creates a new Producto model.
 * If creation is successful, the browser will be redirected to the 'view' page.
 * @return mixed
 */
public function actionCreate()
{
    $model = new Producto();

    if ($model->load(Yii::$app->request->post())){
        if(($productos = ['nombre_producto' => Yii::$app->request->get('nombre_producto')])!=null){
            echo '<script language="javascript">alert("Produdcto already exists");</script>';
        }else {
            if($model->save()){
                return $this->redirect(['index']);
            }
        }
    } else {
        return $this->renderAjax('create', [
            'model' => $model,
        ]);
    }
}

1 个答案:

答案 0 :(得分:0)

这是因为你已经添加了

return $this->renderAjax('create', [
        'model' => $model,
]);

else部分中,脚本位于第一个if

另外,仅使用type="text/javascript"而不是javascript,虽然默认情况下浏览器具有该类型,但您现在也可以跳过该部分并使用

$script=<<<JS
alert("Produdcto already exists");
JS;
$this->getView()->registerJs($js,\yii\web\View::POS_READY)

你应该将你的功能改为

/**
 * Creates a new Producto model.
 * If creation is successful, the browser will be redirected to the 'view' page.
 * @return mixed
 */
public function actionCreate()
{
    $model = new Producto();

    if ($model->load(Yii::$app->request->post())){
        if(($productos = ['nombre_producto' => Yii::$app->request->get('nombre_producto')])!=null){
                  $script=<<<JS
                  alert("Produdcto already exists");
                  JS;
                  $this->getView()->registerJs($js,\yii\web\View::POS_READY)
        }else {
            if($model->save()){
                return $this->redirect(['index']);
            }
        }
    } 

    return $this->renderAjax('create', [
        'model' => $model,
    ]);
}