使用json_encode输出换行符或换行符?
我是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,还是必须使用数组?
我也尝试过使用
。
编辑:
我输出以下方式:
$.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之前,在客户端,你需要用
替换换行符或使用white-space: pre
。 或者你可以使用段落
标签包围每一行。 这样做看看: jQuery text()和换行符 。
回顾这个问题,对我来说,解决方案的简单性变得非常痛苦。 我遇到这么困难的原因是因为我需要使用html
格式。
当然它不尊重
,我把它格式化为文本! 这是我处理这种情况最简单的方法。
array( 'status' => 'failed', 'message' => "Website needs to be in the following formats:
www.website.com
website.com
website.net/something" ), JSON_PRETTY_PRINT); $(".content_status").html(response.message).slideDown("normal");