首页 > 解决方案 > Yii2 无效的 JSON 数据。何时验证另一个功能

问题描述

所有 Yii2 版本 2.0.15.1 php 7.0.27

我不知道为什么会发生这个错误。我重新检查了这个错误:无效的 JSON 数据,只有在执行验证函数 checkAva 时才会出现。

这是我的代码

MyModel.php

public function rules(){
    return [
     [['docs'],'file','maxFiles'=>10,'skipOnEmpty'=>true],
     [['available'], 'checkAva','skipOnEmpty' => true,'on'=>'create'],] // if this validation activated error will come out 
}

函数 checkAva

public function checkAva($attribute, $params)
    {
        $caid = $this->budget_id;
        $available  = Budget::find()
                ->select(['available'])
                ->where('id = :caid', [':caid' => $caid])
                ->one();
        if ($this->available != $available->available){
         $this->addError('available', 'pls change');
        }
    }

函数初始预览

public function initialPreview($data,$field,$type='file'){
        $initial = [];
        $files = Json::decode($data);
        if(is_array($files)){
            foreach ($files as $key => $value) {
                if($type=='file'){
                    $initial[] = "<div class='file-preview-other'><h2><i class='glyphicon glyphicon-file'></i></h2></div>";
                }elseif($type=='config'){
                    $initial[] = [
                        'caption'=> $value,
                        'width'  => '1200px',
                        'url'    => Url::to(['/memo/deletefile','id'=>$this->id,'fileName'=>$key,'field'=>$field]),
                        'key'    => $key
                    ];
                }
                else{
                    $initial[] = Html::img(self::getUploadUrl().$this->ref.'/'.$value,['class'=>'file-preview-image', 'alt'=>$model->file_name, 'title'=>$model->file_name]);
                }
            }
        }
        return $initial;
    }

_形式

use yii\helpers\Json;
use kartik\widgets\FileInput;
                    <?= $form->field($model, 'docs[]')->widget(FileInput::classname(), [
                        'options' => [
                            //'accept' => 'image/*',
                            'multiple' => true
                        ],
                        'pluginOptions' => [
                           'initialPreview'=>$model->initialPreview($model->docs,'docs[]','file'),  // if comment this code no error come out I thing it something about formatter?
                           'initialPreviewConfig'=>$model->initialPreview($model->docs,'docs','config'), // if comment this code no error come out I thing it something about formatter?
                            'allowedFileExtensions'=>['pdf','doc','docx','xls','xlsx','jpeg','png','jpg','txt','rtf','tiff','tif'],
                            'initialPreviewAsData'=>true,
                            'maxFileSize'=>15000,
                            'showPreview' => true,
                            'showCaption' => true,
                            'showRemove' => true,
                            'showUpload' => false,
                            'overwriteInitial'=>true
                         ]
                        ]); ?>

在控制器 $model->docs 将调用 uploadMultipleFile

  public function actionCreate()
     {

    $model->docs = $this->uploadMultipleFile($model);
     }


private function uploadMultipleFile($model,$tempFile=null){
             $files = [];
             $json = '';
             $tempFile = Json::decode($tempFile);
             $UploadedFiles = UploadedFile::getInstances($model,'docs');
             if($UploadedFiles!==null){
                foreach ($UploadedFiles as $file) {
                    try {   $oldFileName = $file->basename.'.'.$file->extension;
                            $newFileName = md5($file->basename.time()).'.'.$file->extension;
                            $file->saveAs(Memoopex::UPLOAD_FOLDER.'/'.$model->ref.'/'.$newFileName);
                            $files[$newFileName] = $oldFileName ;
                    } catch (Exception $e) {
                        //
                    }
                }
                $json = json::encode(ArrayHelper::merge($tempFile,$files));
             }else{
                $json = $tempFile;
             }
            return $json;
    }

错误画面 在此处输入图像描述

标签: jsonvalidationyii2

解决方案


JSON解码时需要提供数据,JSON::decode()因此您的线路

'initialPreview'=>$model->initialPreview($model->docs,'docs[]','file'), 

正在发送$model->docs需要有效的参数,json因为您在函数中对其进行解码initialPreview()

 $files = Json::decode($data);

$data在您的情况下无效JSON,请确保您有一个有效的 JSON 字符串并且它将起作用。


推荐阅读