[英]JSON.parse with json_encode and html
I have got the following html string: $htmlString = '<div class="foo">bar</div>';
我有以下html字符串: $htmlString = '<div class="foo">bar</div>';
I would like to json_encode this string and parse this in a javascript variable, using the following code: JSON.parse('<?= json_encode($htmlString, JSON_HEX_QUOT | JSON_HEX_TAG); ?>')
我想使用以下代码对这个字符串进行json_encode并将其解析为javascript变量: JSON.parse('<?= json_encode($htmlString, JSON_HEX_QUOT | JSON_HEX_TAG); ?>')
Unfortunaly, my javascript returns an error ( Unexpected token f
) because the double quote in the class declaration breaks the json string. 不幸的是,由于类声明中的双引号中断了json字符串,因此我的JavaScript返回了错误( Unexpected token f
)。
Important: This is a simplified version of the array I am actually encoding in JSON. 重要提示:这是我实际上在JSON中编码的数组的简化版本。 The affected string is just a small part of a complex multilevel array. 受影响的字符串只是复杂的多级数组的一小部分。
Changing $htmlString = '<div class="foo">bar</div>';
更改$htmlString = '<div class="foo">bar</div>';
to $htmlString = "<div class='foo'>bar</div>";
为$htmlString = "<div class='foo'>bar</div>";
would be an option, but a bulky one (I would have to change about 500 views) 将是一个选择,但体积很大(我必须更改约500个视图)
Does anyone have another solution? 有人有其他解决方案吗?
You don't need to JSON.parse
. 您不需要JSON.parse
。 You can do like this: 您可以这样:
<script>
var html = <?= json_encode($htmlString) ?>;
</script>
The result of json_encode
already contains valid javascript data. json_encode
的结果已经包含有效的javascript数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.