【问题标题】:Sending html code through json from php to javascript通过json从php发送html代码到javascript
【发布时间】:2017-04-28 07:13:28
【问题描述】:

我在 JS 中遇到以下错误: SyntaxError: 意外的标记

如何通过 JSON 正确发送 HTML 代码(它是一个完整的页面)。 我没有这个想法,但这是我正在尝试安装的插件,我收到了这个错误。因此,如果有人能指出我这里出了什么问题以及如何解决它,那就太好了。谢谢。

    public function ajaxfilter()
{
    $this->registry->set('bf_force_tmp_table_creation', true);
    $data = $this->_prepareFilterInitialData();

    $json = array();
    $route = $this->_getRequestParam('curRoute');
    if ($route && $this->_getRequestParam('withContent')) {
        $this->request->get['route'] = $route;
        $this->load->controller($route, $data);
        $json['products'] = $this->response->getOutput();
    }

    $this->load->model('module/brainyfilter');
    $model = new ModelModuleBrainyFilter($this->registry);

    $model->setData($data);

    if ((bool)$this->_getRequestParam('count', false)) {
        $json['brainyfilter'] = $model->calculateTotals();
    }
    if ((bool)$this->_getRequestParam('price', false)) {
        $minMax = $model->getMinMaxCategoryPrice();
        $min = floor($this->currency->format($minMax['min'], $this->_currency, '', false));
        $max = ceil($this->currency->format($minMax['max'], $this->_currency, '', false));
        $json['min'] = $min;
        $json['max'] = $max;
    }
    $this->log->debug($json);
    $isMijoShop = class_exists('MijoShop') && defined('JPATH_MIJOSHOP_OC');
    if ($isMijoShop) {
        header('Content-Type: application/json');
        die(json_encode($json));
    } else {
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
}

【问题讨论】:

  • 首先,请向我们展示导致此错误的代码。其次,为什么要通过 JSON 发送 HTML? JSON的整个point是发送一个数据结构来由客户端解释。要么发送整个 HTML 响应(这不是一个好主意),要么按照预期使用 JSON。
  • 在发送之前对您的 html 字符串进行编码。
  • 我说这不是我的主意,这是已经做出来的插件,我想弄清楚为什么它不起作用

标签: javascript php jquery html json


【解决方案1】:

使用json_encode 获取有效的 JSON 字符串。

您可以对任何标量值、数组和stdClass 实例进行编码。对于任何其他类,您可以实现JsonSerializable 接口。

一个简单的 HTML 示例:

<?php
$html = '<div class="container">What-Ever-Content </div>";
echo json_encode($html);

这将产生这个输出:

"<div class=\"container\">What-Ever-Content </div>"

【讨论】:

    猜你喜欢
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 2012-08-21
    • 2013-02-05
    相关资源
    最近更新 更多