作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 AJAX 和 PHP 创建帖子并立即显示它。我的 php 代码可以创建帖子,但我在进行 json 编码以显示刚刚创建的帖子时遇到问题。像这样对 html 进行编码似乎会在每个/之前添加一个\,导致 html 中断并以奇怪的方式显示。 (我使用 json 编码,因为如果出现错误,我需要一个变量来知道它是否是错误,并将错误显示在与帖子不同的位置)
这是我要编码的内容
$data = "<article class='post'><div class='post-head cf'>
<a class='userpic' href=''><img src='$userpic' alt='".$rowuser['username']."'></a>
<a href='' class='username'>".$rowuser['username']."</a></div>
<img src='users/user_".$rowuser['user_id']."/posts/".$row['image']."' alt=''>
<div class='post-body'>
<div class='post-options'>
<a class='likes' href=''>156 likes</a>
</div>
<p><a class='username' href=''>".$rowuser['username']."</a>".$row['body']."</p>
<hr /><div class='cf'>
<a class='like hide-text' href='javascript:;'>Like This Post</a>
<form action='' class='comment'>
<input type='text' placeholder='Add a comment'></form></div>
</div></article>";
echo json_encode($data);
最佳答案
Encoding the html like this seems to add a \ before every / causing the html to break
PHP is escaping the slashes while encoding 。可以通过在调用 json_encode()
时添加 JSON_UNESCAPED_SLASHES
标志来防止这种情况:
$data = "<html></html>";
$escaped = json_encode($data);
// string(16) ""<html><\/html>""
var_dump($escaped);
$unescaped = json_encode($data, JSON_UNESCAPED_SLASHES);
// string(15) ""<html></html>""
var_dump($unescaped);
关于javascript - 如何在 PHP 中对 HTML 进行 JSON 编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41349817/
我是一名优秀的程序员,十分优秀!