我是 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");
}
}
});
最佳答案
使用\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 .
关于javascript - 使用 json_encode 输出换行符或新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25587496/