[英]using json encode on an Object with Escaped characters ( double quotes )
I am using mysqli::real_escape_string on the inputs received from my forms before sending them to the database .在将它们发送到数据库之前,我在从我的表单接收到的输入上使用mysqli::real_escape_string 。
in another page i am receiving these data and converting each row of data into JSON using json_encode
在另一个页面中,我正在接收这些数据并使用json_encode
将每一行数据转换为 JSON
then i am sending them into front-end as response :然后我将它们发送到前端作为响应:
$usersInstance = new usersRepository();
$users = $usersInstance->allUsers();
ob_start();
foreach ($users as $index => $user) {
$userObj = (object) [];
$userObj->id = $user['id'];
$userObj->email = $user['email'];
$userObj->displayname = $user['display_name'];
$userObj->grade = $user['grade'];
$userJson = json_encode($userObj);
$userBox = <<<HTML
<div class="user-box" data-userjson={$userJson}>
<div class="user-cell " >
<span> {$user['email']} </span>
</div>
<div class="user-id-holder" style="visibility:hidden;width:0px;height:0px;overflow:hidden;display:inline-block">
{$user['id']}
</div>
<div class="user-cell" >
<span>{$user['display_name']}</span>
</div>
<div class="user-cell " >
<span>سطح دسترسی : {$user['grade']}</span>
</div>
<div class="user-cell">
<span class="user-action-btn" data-action="edit"><span>ویرایش</span></span>
<span class="user-action-btn" data-action="delete"><span>حذف</span></span>
</div>
</div>
HTML;
echo $userBox;
}
$renderedContent = ob_get_contents();
ob_end_clean();
then i want to access these JSONs in javascript like this然后我想像这样在javascript中访问这些JSON
let UserBox = $(this).parent('div').parent('div.user-box');
let userObj = $(UserBox).data('userjson');
The problem is that when i try access object i get errors and undefined because escaped double quotes represent as "
and it makes the object an invalid JSON , see example output below :问题是,当我尝试访问对象时,我得到错误和未定义,因为转义的双引号表示为"
并且它使对象成为无效的 JSON ,请参阅下面的示例输出:
{"id":"32","email":"test3@gmail.com","displayname":"test'and'more'test"","grade":"2"}
displayname propert has a value that contains double quote which cause object to be invalid. displayname属性的值包含双引号,导致对象无效。
My question is that how can i keep escaped characters escaped when i am using the JSON i want to display the values in html and they become "
when are printed . so actual problem is that how can i seperate "
and "
?我的问题是,当我使用 JSON 时如何保持转义字符转义,我想在 html 中显示值,并且它们变成"
何时打印。所以实际问题是我如何将"
和"
分开?
Use htmlentities to escape the quotes and turn them into "
使用htmlentities转义引号并将它们转换为"
when handling your form data.处理表单数据时。 Then when you get the data back and use json_encode
on it, there should be real double quotes around your JSON stuff and the quotes going in the HTML are "
然后,当您取回数据并在其上使用json_encode
时,您的 JSON 内容应该有真正的双引号,并且 HTML 中的引号是"
, which will be properly parsed and rendered. ,它将被正确解析和呈现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.