本文整理汇总了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);
}
示例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 . ');');
}
示例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
);
}
}
示例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());
}
}
示例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']);
}
示例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;
}
示例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);
}
示例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);
}
示例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));
}
示例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});");
}
示例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);
}
示例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;
}
示例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);
}
示例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);
}
示例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' => '']);
}
}