当前位置: 首页>>代码示例>>PHP>>正文


PHP Json::encode方法代码示例

本文整理汇总了PHP中yii\helpers\Json::encode方法的典型用法代码示例。如果您正苦于以下问题:PHP Json::encode方法的具体用法?PHP Json::encode怎么用?PHP Json::encode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在yii\helpers\Json的用法示例。


在下文中一共展示了Json::encode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: run

    function run()
    {
        parent::run();
        $wid = $this->options['id'];
        echo Html::activeHiddenInput($this->model, $this->attribute);
        echo Html::beginTag('div', ['id' => $wid . '-buttons', 'class' => 'input-group btn-group']);
        $items = PublishBehavior::getPublishedOptions();
        $colors = PublishBehavior::getPublishedColors();
        foreach ($items as $key => $item) {
            echo Html::button($item, ['data' => ['value' => $key], 'class' => $key == $this->model->{$this->attribute} ? 'btn btn-' . $colors[$key] . ' active' : 'btn btn-default']);
        }
        echo Html::endTag('div');
        $js_colors = Json::encode($colors);
        $js = <<<JS
 \$('#{$wid}-buttons').find('button').each(function(){
   \$(this).on('click',function(){
     \$('#{$wid}-buttons').find('button').each(function(){
        \$(this).removeClass('btn-danger btn-warning btn-success btn-info active');
        \$(this).addClass('btn-default');
     });
     var color={$js_colors};
     \$(this).removeClass('btn-default');
     \$(this).addClass('btn-'+color[\$(this).data('value')]+' active');
     \$('#{$wid}').val(\$(this).data('value'))
   });  
});               
JS;
        $this->view->registerJs($js);
    }
开发者ID:claudejanz,项目名称:yii2-toolbox,代码行数:29,代码来源:PublishWidget.php

示例2: registerClientScript

 /**
  * Register widget client scripts.
  */
 protected function registerClientScript()
 {
     $view = $this->getView();
     $options = Json::encode($this->jsOptions);
     Asset::register($view);
     $view->registerJs('jQuery.comment(' . $options . ');');
 }
开发者ID:frenzelgmbh,项目名称:cm-comments,代码行数:10,代码来源:Comments.php

示例3: run

    public function run()
    {
        //Если данные по доставке закешированы просто рисуем их иначе делаем ajax запрос, чтобы заполнился кеш
        if (\Yii::$app->v3toysSettings->isCurrentShippingCache) {
            return $this->render($this->viewFile);
        } else {
            $js = \yii\helpers\Json::encode(['backend' => \yii\helpers\Url::to('/v3toys/cart/get-current-shipping')]);
            $this->view->registerJs(<<<JS
    (function(sx, \$, _)
    {
        sx.classes.GetShipping = sx.classes.Component.extend({

            _onDomReady: function()
            {
                var self = this;

                _.delay(function()
                {
                    sx.ajax.preparePostQuery(self.get('backend')).execute();
                }, 500);
            }
        });

        new sx.classes.GetShipping({$js});

    })(sx, sx.\$, sx._);
JS
);
        }
    }
开发者ID:v3toys,项目名称:skeeks,代码行数:30,代码来源:V3toysDeliveryFastWidget.php

示例4: run

 public function run($id)
 {
     $model = $this->getNodeById($id);
     $model->scenario = 'move';
     $model->load(Yii::$app->request->post(), '');
     if (!$model->validate()) {
         throw new HttpException(500, current(current($model->getErrors())));
     }
     if (!$model->relatedNode instanceof $this->treeModelName) {
         throw new NotFoundHttpException(Yii::t('gtreetable', 'Position indicated by related ID is not exists!'));
     }
     try {
         if (is_callable($this->beforeAction)) {
             call_user_func_array($this->beforeAction, ['model' => $model]);
         }
         $action = $this->getMoveAction($model);
         if (!call_user_func(array($model, $action), $model->relatedNode)) {
             throw new Exception(Yii::t('gtreetable', 'Moving operation `{name}` failed!', ['{name}' => Html::encode((string) $model)]));
         }
         if (is_callable($this->afterAction)) {
             call_user_func_array($this->afterAction, ['model' => $model]);
         }
         echo Json::encode(['id' => $model->getPrimaryKey(), 'name' => $model->getName(), 'level' => $model->getLevel(), 'type' => $model->getType()]);
     } catch (\Exception $e) {
         throw new HttpException(500, $e->getMessage());
     }
 }
开发者ID:antiqwerty,项目名称:yii2-gtreetable-fix,代码行数:27,代码来源:NodeMoveAction.php

示例5: up

 public function up()
 {
     mb_internal_encoding("UTF-8");
     $tableOptions = $this->db->driverName === 'mysql' ? 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB' : null;
     $this->createTable('{{%wysiwyg}}', ['id' => Schema::primaryKey(), 'name' => Schema::string()->notNull(), 'class_name' => Schema::string()->notNull(), 'params' => Schema::text(), 'configuration_model' => Schema::string()], $tableOptions);
     $this->insert('{{%wysiwyg}}', ['name' => 'Imperavi', 'class_name' => 'vova07\\imperavi\\Widget', 'params' => Json::encode(['settings' => ['replaceDivs' => false, 'minHeight' => 200, 'paragraphize' => false, 'pastePlainText' => true, 'buttonSource' => true, 'imageManagerJson' => Url::to(['/backend/dashboard/imperavi-images-get']), 'plugins' => ['table', 'fontsize', 'fontfamily', 'fontcolor', 'video', 'imagemanager'], 'replaceStyles' => [], 'replaceTags' => [], 'deniedTags' => [], 'removeEmpty' => [], 'imageUpload' => Url::to(['/backend/dashboard/imperavi-image-upload'])]]), 'configuration_model' => 'app\\modules\\core\\models\\WysiwygConfiguration\\Imperavi']);
 }
开发者ID:kronos777,项目名称:dotplant2,代码行数:7,代码来源:m150717_123227_selectable_wysiwyg.php

示例6: actionNotify

 public function actionNotify($id)
 {
     $response = ['result' => 'false', 'returnCode' => '500', 'message' => '失败'];
     $express = Express::findOne($id);
     if ($express && isset($_POST['param'])) {
         $param = Json::decode($_POST['param']);
         if (isset($param['lastResult']) && $express->company == $param['lastResult']['com'] && $express->number == $param['lastResult']['nu'] && (empty($express->auth_key) || isset($_POST['sign']) && $this->module->manager->verify($_POST['sign'], $_POST['param'], $express->auth_key))) {
             $express->status = $this->module->manager->getStatus($param['lastResult']['state']);
             $express->details = Json::encode($param['lastResult']['data']);
             if ($param['lastResult']['ischeck'] == 1 && $param['lastResult']['state'] == 3) {
                 $express->receipted_at = strtotime($param['lastResult']['data'][0]['time']);
             }
             if ($express->save()) {
                 $response['result'] = 'true';
                 $response['returnCode'] = '200';
                 $response['message'] = '成功';
                 if ($notifyClass = $this->module->notifyClass) {
                     $notifyClass::receipted($id);
                 }
             }
         }
     }
     \Yii::$app->response->format = 'json';
     return $response;
 }
开发者ID:xiewulong,项目名称:yii2-express,代码行数:25,代码来源:Kd100Controller.php

示例7: getPluginOptions

 /**
  * Return plugin options in json format
  * @return string
  */
 public function getPluginOptions()
 {
     if (!isset($this->pluginOptions['type'])) {
         $this->pluginOptions['type'] = $this->type;
     }
     return Json::encode($this->pluginOptions);
 }
开发者ID:heartshare,项目名称:yii2-ion-slider,代码行数:11,代码来源:IonSlider.php

示例8: registerJs

 protected function registerJs($selector, $options, $callback)
 {
     $view = $this->getView();
     DateRangePickerAsset::register($view);
     $js = '$("' . $selector . '").daterangepicker(' . Json::encode($options) . ($callback ? ', ' . Json::encode($callback) : '') . ');';
     $view->registerJs($js, View::POS_READY);
 }
开发者ID:VEKsoftware,项目名称:daterangepicker,代码行数:7,代码来源:DateRangePicker.php

示例9: actionAjaxGet

 public function actionAjaxGet()
 {
     $page = (int) \Yii::$app->request->get('page', 1);
     $pageSize = (int) \Yii::$app->request->get('rows', 20);
     $result = (new FriendLink())->getDataByPage($page, $pageSize);
     exit(Json::encode($result));
 }
开发者ID:styleyoung,项目名称:taoshop,代码行数:7,代码来源:FriendLinkController.php

示例10: registerAssets

 protected function registerAssets()
 {
     ClockPickerAsset::register($this->view);
     $inputId = "#{$this->options['id']}";
     $pluginOptions = !empty($this->pluginOptions) ? Json::encode($this->pluginOptions) : '{}';
     $this->view->registerJs("jQuery('{$inputId}').clockpicker({$pluginOptions});");
 }
开发者ID:madand,项目名称:yii2-clockpicker,代码行数:7,代码来源:ClockPicker.php

示例11: run

 public function run()
 {
     $this->defaultLabel = Yii::t('app', $this->defaultLabel);
     self::$count++;
     if ($this->id === null) {
         $this->id = 'multi-select-' . self::$count;
     }
     if ($this->name === null) {
         $this->name = $this->model->formName() . '[' . $this->attribute . '][]';
     }
     $list = [$this->defaultIndex => $this->defaultLabel] + $this->items;
     $table = $this->getSelectedItems($this->items);
     $params = ['list' => $list, 'table' => $table, 'label' => $this->label, 'id' => $this->id, 'name' => $this->name, 'ajax' => $this->ajax, 'sortable' => $this->sortable];
     $view = $this->getView();
     // @todo
     // $errorFunction =
     $json = \yii\helpers\Json::encode(['addUrl' => $this->addUrl, 'ajax' => $this->ajax, 'defaultIndex' => $this->defaultIndex, 'removeUrl' => $this->removeUrl, 'selectedItems' => $this->selectedItems, 'ajaxData' => $this->ajaxData, 'errorFunction' => new JsExpression($this->errorFunction), 'successFunction' => new JsExpression($this->successFunction)]);
     if (self::$count == 1) {
         $view = $this->getView();
         JuiAsset::register($view);
         $view->registerJs("jQuery.fn.multiSelect = function(params){\n                var \$multiSelect = \$(this);\n                for(var key in params.selectedItems){\n                    \$multiSelect.find('select.list option[value=\"' + params.selectedItems[key] + '\"]').eq(0).addClass('hidden');\n                }\n                \$multiSelect.on('click', 'table a.remove', function(){\n                    \$this = \$(this);\n                    var \$tr = \$this.parents('tr').eq(0);\n                    var \$td = \$tr.find('td').eq(0);\n                    if(params.ajax){\n                        var data = params.ajaxData;\n                        data.id = \$tr.attr('data-id');\n                        \$.ajax({\n                            'data' : data,\n                            'dataType' : 'json',\n                            'success' : function(data){\n                                if(data.status == 1){\n                                    \$multiSelect.find('select.list').find('option[value=\"' + \$tr.attr('data-id') + '\"]').removeClass('hidden');\n                                    \$tr.remove();\n                                    params.successFunction(data);\n                                }else{\n                                    params.errorFunction(data);\n                                }\n                            },\n                            'type' : 'get',\n                            'url' : params.removeUrl\n                        });\n                    }else{\n                        \$multiSelect.find('select.hidden').find('option[value=\"' + \$tr.attr('data-id') + '\"]').remove();\n                        \$tr.remove();\n                        \$multiSelect.find('select.list').find('option[value=\"' + \$tr.attr('data-id') + '\"]').removeClass('hidden');\n                    }\n                    return false;\n                }).on('change', 'select', function(){\n                    var \$this= \$(this);\n                    if(\$this.val() != params.defaultIndex){\n                        var \$item = \$this.find('option[value=\"' + \$this.val() + '\"]');\n                        var \$table = \$multiSelect.find('table').eq(0);\n                        var \$clone = \$table.find('tr.hidden').eq(0).clone().removeClass('hidden').attr('data-id', \$this.val());\n                        \$clone.find('td').eq(0).text(\$item.text());\n                        \$input = \$('<input type=hidden>').val(\$this.val()).attr(\"name\", \"" . $this->name . "\");\n                        \$clone.append(\$input);\n                        if(params.ajax){\n                            var data = params.ajaxData;\n                            data.id = \$this.val();\n                            \$.ajax({\n                                'data' : data,\n                                'dataType' : 'json',\n                                'success' : function(data){\n                                    if(data.status == 1){\n                                        \$item.addClass('hidden');\n                                        \$clone.appendTo(\$table);\n                                        \$this.find('option[value=\"' + params.defaultIndex + '\"]').attr('selected', 'selected');\n                                        params.successFunction(data);\n                                    }else{\n                                        params.errorFunction(data);\n                                    }\n                                },\n                                'tyte' : 'get',\n                                'url' : params.addUrl\n                            });\n                        }else{\n                            \$('<option></option>').attr('value', \$this.val()).attr('selected', 'selected').text(\$item.text()).appendTo(\$multiSelect.find('select.hidden').eq(0));\n                            \$item.addClass('hidden');\n                            \$clone.appendTo(\$table);\n                        }\n                    }\n                });\n                }", View::POS_END);
     }
     $view->registerJs("jQuery('#" . $this->id . "').multiSelect(" . $json . ");");
     if ($this->sortable) {
         $view->registerJs("jQuery('#" . $this->id . " table tbody').sortable({placeholder: \"ui-state-highlight\"});");
     }
     echo $this->render('multiSelect', $params);
 }
开发者ID:heartshare,项目名称:dotplant2,代码行数:28,代码来源:MultiSelect.php

示例12: save

 /**
  * @param bool $returnJson
  * @return bool|string
  */
 public function save($returnJson = true)
 {
     $primaryKeys = $this->model->primaryKey();
     $primaryKey = $primaryKeys[0];
     $operation = \Yii::$app->getRequest()->post($this->oper);
     if ($operation == 'edit') {
         $id = \Yii::$app->getRequest()->post($primaryKey);
         if (empty($id)) {
             $id = \Yii::$app->getRequest()->post('id');
         }
         if (empty($id) || !($this->model = $this->model->findOne($id))) {
             return $returnJson ? $this->renderJson() : false;
         }
     }
     if (in_array($operation, ['edit', 'add'])) {
         $this->model->setAttributes(\Yii::$app->getRequest()->post());
         $result = $this->model->save();
         return $returnJson ? $this->renderJson() : $result;
     }
     if ($operation == 'del') {
         $ids = \Yii::$app->getRequest()->post('id');
         if ($ids) {
             $ids = explode(',', $ids);
             if ($this->model->deleteAll([$primaryKey => $ids])) {
                 return Json::encode(['success' => 1, 'message' => \Yii::t('yincart', 'Delete Success!')]);
             }
         }
         return Json::encode(['success' => 0, 'message' => \Yii::t('yincart', 'Error ID!'), 'errors' => []]);
     }
     return false;
 }
开发者ID:ASDAFF,项目名称:yincart2-framework,代码行数:35,代码来源:JqForm.php

示例13: registerJs

    public function registerJs($inputId, $dropzoneId)
    {
        $settings = $this->defaults;
        $request = Yii::$app->request;
        if ($request->enableCsrfValidation) {
            $settings['params'] = [$request->csrfParam => $request->getCsrfToken()];
        }
        $successCallback = <<<JS
        function (file, data){
            if (data.uploadId) {
                file.uploadId = data.uploadId;
                \$('#{$inputId}').val(data.uploadId);
            }
        }
JS;
        $settings['success'] = new JsExpression($successCallback);
        $removeCallback = <<<JS
        function (file){
            if(confirm('Are you sure want to remove file?')){
                if(file.uploadId){
                    \$.post('{$settings['removeUrl']}', {
                        uploadId:file.uploadId
                    }).success(function(data){
                        if(\$('#{$inputId}').val() == data.id){
                           \$('#{$inputId}').val('');
                        }
                    })
                }
                if (file.previewElement && file.previewElement.parentNode) {
                    file.previewElement.parentNode.removeChild(file.previewElement);
                }
                return this._updateMaxFilesReachedClass();
            } else {
                return false;
            }


        }
JS;
        $settings['removedfile'] = new JsExpression($removeCallback);
        $existingFiles = [];
        if ($this->existingFile) {
            $existingFiles = [$this->existingFile->uploadInfo];
        }
        $encodedExistingFiles = Json::encode($existingFiles);
        $encodedConfig = Json::encode($settings);
        $init = <<<JS
        Dropzone.autoDiscover = false;
        var dz = new Dropzone("#{$dropzoneId}", {$encodedConfig});
        var files = {$encodedExistingFiles};
        files.forEach(function(file){
            dz.emit("addedfile", file);
            dz.emit("thumbnail", file, file.url);
            dz.emit("complete", file);
        })
        dz.options.maxFiles = dz.options.maxFiles - files.length;
JS;
        DropzoneAsset::register(Yii::$app->view);
        Yii::$app->view->registerJS($init);
    }
开发者ID:griga,项目名称:m22-cms,代码行数:60,代码来源:DropzoneWidget.php

示例14: run

    /**
     * @inheritdoc
     */
    public function run()
    {
        echo Html::tag('div', null, ['id' => $this->containerId, 'style' => 'display:none']);
        $view = $this->getView();
        PushStreamAsset::register($view);
        $options = Json::encode($this->pluginOptions);
        $channels = '';
        foreach ((array) $this->channels as $channel) {
            $channels .= $this->pusher . ".addChannel('{$channel}');";
        }
        $js = <<<JS
            var {$this->pusher} = new PushStream({$options});
            {$channels}
            {$this->pusher}.onmessage = function (text, id, channel) {
                \$.each(text.events, function (index, event) {
                    \$('#{$this->containerId}').trigger({
                        channel: channel,
                        type: event.name,
                        body: event.body
                    });
                });
            };
JS;
        if ($this->connect) {
            $js .= $this->pusher . '.connect();';
        }
        $view->registerJs($js);
    }
开发者ID:dizews,项目名称:yii2-push-stream,代码行数:31,代码来源:PushStreamWidget.php

示例15: actionSubcat

 public function actionSubcat()
 {
     $out = [];
     $isEmpty = true;
     if (isset($_POST['depdrop_parents'])) {
         $parents = $_POST['depdrop_parents'];
         if ($parents != null) {
             $cat_id = $parents[0];
             $out = Group::getDropDownList($cat_id);
             //$out = [['id'=>'1', 'name'=>$cat_id],['id'=>'2', 'name'=>json_encode(Group::getDropDownList($cat_id))]];
             $isEmpty = false;
             $selected = '';
             if (!empty($_POST['depdrop_params'])) {
                 $params = $_POST['depdrop_params'];
                 $selected = $params[0];
                 // get the value of input-type-1
                 $param2 = $params[1];
                 // get the value of input-type-2
             }
             echo Json::encode(['output' => $out, 'selected' => $selected]);
         }
     }
     if ($isEmpty) {
         echo Json::encode(['output' => [['id' => '1', 'name' => '<sub-cat-name1>'], ['id' => '2', 'name' => '<sub-cat-name2>']], 'selected' => '']);
     }
 }
开发者ID:devpopov,项目名称:study-online-service-public,代码行数:26,代码来源:RegistrationController.php


注:本文中的yii\helpers\Json::encode方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。