【问题标题】:Output line breaks or new lines with json_encode?使用 json_encode 输出换行符或换行符?
【发布时间】:2014-10-24 14:23:57
【问题描述】:

我是 JSON 格式的新手,所以请原谅我缺乏知识。但不知何故,我需要在我的 json_encode 数组中添加一些换行符,以便它可以解析多行。我已经搜索和搜索,但没有什么适合我的情况。

输出为:

Following formats accepted: www.website.com website.com website.net/something

但我希望像这样输出数据:

Website needs to be in the following formats:  
www.website.com  
website.com  
website.net/something

我试过了:

echo json_encode( 
    array( 'status' => 'failed',
           'message' => "Website needs to be in the following formats:\n
            www.website.com\n
            website.com\n
            website.net/something"
    ), JSON_PRETTY_PRINT);

但 Javascript 将其解析为文字字符串,因此换行符被忽略并输出。我可以使用直接 JSON 格式将数据从 PHP 发送到 javascript,还是必须使用数组?

我也尝试过使用<br />

编辑:
我正在输出以下方式:

$.ajax({
    url: "/forms/content_process.php",
    type:'POST',
    data: $(".content_cat").serialize(),
    processData: false,
    dataType: "json",
    success: function(response) {
        if (response.status == "failed") {
            $(".content_status").css( "background-color", "red" );
            $(".content_status").text(response.message).slideDown("normal");
        } else {
            $(".content_status").css( "background-color", "green" );
            $(".content_status").text("Your category was submitted!").slideDown("normal");
        }
    }
});

【问题讨论】:

  • 除了无效的双重转义外,您已经通过将字符串包装成多行来嵌入换行符。而是查看输出的 JSON 及其用途,并详细说明它与您的预期有何不同。
  • @Charlotte Dunois - 我试过 \n 和 \\n
  • 尝试组合选项json_encode($your_array, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
  • 你想如何输出消息?如果它被插入到 DOM 中,大多数元素会将空格(包括换行符)压缩为一个空格。 <pre> 和其他样式以 white-space 为典型例外。
  • 将 \\n 替换为
    ,因为
    是 (X)HTML 中的新行。

标签: javascript php jquery json


【解决方案1】:

使用\n 在字符串中插入换行符。也不要添加真正的换行符。

echo json_encode( 
    array( 'status' => 'failed',
           'message' => "Website needs to be in the following\nformats:\nwww.website.com\nwebsite.com\nwebsite.net/something"
    ), JSON_PRETTY_PRINT);

在将其插入 dom 之前在客户端,您需要将换行符替换为 <br /> 或使用 white-space: pre。或者,您可以用段落<p></p> 标签包围每一行。这样做看看这里:jQuery text() and newlines

【讨论】:

  • 你成功了@dreamlab。我永远不会想到这一点。
【解决方案2】:

回头看这个问题,我很痛苦地发现解决方案是多么简单。我之所以遇到这样的困难,是因为我需要使用html格式。

当然,这不尊重<br />,我将其格式化为文本!对于我的情况,这是最简单的方法。

array( 'status' => 'failed',
       'message' => "Website needs to be in the following formats:<br />
        www.website.com<br />
        website.com<br />
        website.net/something"
), JSON_PRETTY_PRINT);

$(".content_status").html(response.message).slideDown("normal");

【讨论】:

    猜你喜欢
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 2017-09-05
    相关资源
    最近更新 更多