使用json_encode如何输出换行符或新行?

4

我是一个对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");
        }
    }
});

1
除了无效的双重转义之外,您已经通过将字符串分成多行来嵌入换行符。相反,请查看输出的JSON及其使用方式,并详细说明它与您的期望有何不同。 - mario
1
尝试结合选项 json_encode($your_array, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) - PauloASilva
1
你是如何尝试输出消息的?如果它被插入到DOM中,大多数元素将压缩空白,包括换行符,只保留一个空格。<pre>和其他使用white-space样式的元素通常是例外。 - Jonathan Lonowski
1
将 \n 替换为 <br />,因为在 (X)HTML 中 <br /> 表示换行。 - Charlotte Dunois
@EternalHour 请展示一下你尝试输出的方式。 - Charlotte Dunois
显示剩余2条评论
2个回答

14

使用\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


1
你太厉害了,@dreamlab。我永远也想不到那个。 - EternalHour

1
回顾这个问题,对我来说解决方案是如此简单,让人感到痛苦。我之所以遇到困难,是因为我需要使用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");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接