這個問題已被問過幾次,答案似乎是使用,json_encode但這不起作用,因為我的字符串包含的內容比引號多。這是 PHP 字符串:<img src="test.jpg" :class="{ 'add-class': comment == 1, 'another-class': comment == 2 }" x-on:click="submit()">和是AlpineJS屬性,以防您想知道(檢查一下,它真的很酷?。?class。x-on:這個 PHP 字符串是動態生成的,我想將它傳遞給一個 javascript 變量,如下所示jsVariable:<script>function test() { return { jsVariable: , anotherVariable: true, }}</script>更新如果我使用jsVariable: <?php echo json_encode($php_variable); ?>,我在該行得到 SyntaxError: Unexpected token '&' 。如果我使用jsVariable: '<?php echo json_encode($php_variable); ?>',(添加單引號)然后變量被解析為字符串而不是 HTML。
2 回答

不負相思意
TA貢獻1777條經驗 獲得超10個贊
使用json_encode():
<script>
function test() {
return {
jsVariable: <?php echo json_encode($php_variable); ?>,
anotherVariable: true,
}
}
</script>

慕萊塢森
TA貢獻1810條經驗 獲得超4個贊
如果只是用ASCII編碼,可以試試base64編碼。
PHP 將字符串編碼為 base64,然后使用 Javascript 進行解碼,如下所示:
<script>
function test(){
var str = '<?php echo base64_encode($str);?>';
return {
jsVariable: atob(str),
anotherVariable: true
}
}
alert(test().jsVariable)
</script>
希望這可以幫助。
- 2 回答
- 0 關注
- 137 瀏覽
添加回答
舉報
0/150
提交
取消