【问题标题】:Output HTML in JSON string generated by PHP以 PHP 生成的 JSON 字符串输出 HTML
【发布时间】:2013-08-08 15:43:36
【问题描述】:

我有一些输出 json 的 PHP。

<?php
$html = utf8_encode($gegevens['tekst']);
$html = htmlentities($html);
//$html = htmlspecialchars($gegevens['tekst'], ENT_QUOTES, 'UTF-8');
echo json_encode(array( 'titel' => $gegevens['titel'], 'html' => $html ));
?>

输出会是这样的:

{"titel":"Here comes the title","html":"<strong>Here is the HTML<\/strong>\n<br \/>\n<br \/>\n     And some more."}

jQuery/Ajax 将是:

$.ajax({
                            type: "GET",
                            url: "content/popup.php?id=" + id2,
                            dataType: 'json',
                            crossDomain: true,
                            success: function(json) {
                            var titel = json['titel'];
                            var html = json['html'];


function ContentTonen()
{
                                // Div's legen van content
$('.popup_home_head_inside').empty();
$('.popup_home_content_inside').empty();

$('.popup_home_head_inside').html(titel);
var html2 = html.replace(/\"/g, "");
//$('.popup_home_content_inside').html(html2);
$('.popup_home_content_inside').html(html2);

HTML 输出为:

<strong>Some HTML</strong> <br /> Some more text.

所以它不会作为 HTML 处理。

你能帮帮我吗?

【问题讨论】:

    标签: php jquery html json


    【解决方案1】:

    您无需在服务器端使用 htmlentities 转义 html。

    从您的 php 文件中删除 $html = htmlentities($html);

    原因: htmlentities 将转换

    <strong>Some HTML</strong> <br /> Some more text.
    

    &lt;strong&gt;Some HTML&lt;/strong&gt; &lt;br /&gt; Some more text.
    

    包含在 html 中时会显示:

    <strong>Some HTML</strong> <br /> Some more text.
    

    【讨论】:

    • 那我该如何为 JSON 准备 html 呢? Stripslashes 不起作用。
    • 你的意思是什么准备?
    • 当我将 HTML 直接插入 JsonEncode 时,它​​返回 null。因为它不是有效的 JSON。使用 htmlentities JsonEncode 接受字符串作为有效的 JSON。但是我应该使用哪个函数来准备 HTML 为有效的 JSON?
    • 请试试这个。 &lt;?php $html = utf8_encode($gegevens['tekst']); echo json_encode(array( 'titel' =&gt; $gegevens['titel'], 'html' =&gt; $html )); ?&gt;
    • 如此简单,如此有效。谢谢你救了我!
    猜你喜欢
    • 2018-04-04
    • 1970-01-01
    • 2019-03-05
    • 2010-09-15
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    相关资源
    最近更新 更多