JSON.parse与json_encode和html

I have got the following html string: $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); ?>')

Unfortunaly, my javascript returns an error (Unexpected token f) because the double quote in the class declaration breaks the json string.

Important: This is a simplified version of the array I am actually encoding in JSON. The affected string is just a small part of a complex multilevel array.

Changing $htmlString = '<div class="foo">bar</div>'; to $htmlString = "<div class='foo'>bar</div>"; would be an option, but a bulky one (I would have to change about 500 views)

Does anyone have another solution?

1个回答

You don't need to JSON.parse. You can do like this:

<script>
var html = <?= json_encode($htmlString) ?>;
</script>

The result of json_encode already contains valid javascript data.

dongshou9343
dongshou9343 有时候生活很简单,我值得一个醒来的额头一巴掌
5 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐