如何在Json编码Yii2中消除null值?

时间:2019-03-10 03:55:04

标签: php jquery json yii2

我正在尝试创建或更新模态模型,而在Json之后答案将为空,并且在执行该操作后不会隐藏我的模态。网络显示此

  

SyntaxError:JSON.parse:JSON数据第1行第103列的JSON数据后出现意外的非空白字符

{"status":true,"type":"success","title":"¡Excelente!","msj":"Se han guardado los datos correctamente"}null之后,结尾为null,这是什么意思? enter image description here

我的动作如下:

public function run($id = null)
{
    if ($id == null) {
        $model = new BancosConcepto();
    } else {
        $model = BancosConcepto::findOne($id);
    }

    $model->loadDefaultValues();
    $show_form = true;

    $data = array();
    if (Yii::$app->request->isPost) {
        $model->load(Yii::$app->request->post());

        if($model->save()) {
            $show_form = false;
            $data['status'] = true;
            $data['type'] = 'success';
            $data['title'] = '¡Excelente!';
            $data['message'] = 'El concepto se registró correctamente.';
        }
    }

    if ($show_form) {
        return $this->controller->renderAjax('_form', [
            'model' => $model,
        ]);
    } else {
        Yii::$app->response->format = Response::FORMAT_JSON;
        echo JSON::encode($data);
    }
}

我的视图如下:

$( document ).on( "click", ".btn-add", function(e) {

    url = $(this).attr('href');
    $.ajax({
        type: "GET",
        url: url,
        beforeSend: function() {    
            $("#modal-win .modal-dialog").addClass("modal-sm")
            $("#modal-win").modal('show');
        },
        success: function(data){
            $("#modal-win .modal-content").html(data);
        }
    });
    return false;

});

1 个答案:

答案 0 :(得分:0)

您的操作应返回响应,而不是回显它:

if ($show_form) {
    return $this->controller->renderAjax('_form', [
        'model' => $model,
    ]);
} else {
    return $this->controller->asJson($data);
}