参见英文答案 > Pass a PHP string to a JavaScript variable (and escape newlines) 14个
我在PHP中有一个foreach循环:
var circle_<?php echo $x; ?> = '<?php echo $c; ?>';
它在JavaScript中返回:
var circle_0 = '<p class="medium">With us, you can customize more than just a closet.</p>';
var circle_1 = '<p class="medium">We are boutique condo builders who love what we do.</p>';
var circle_2 = '<p class="medium">who says condos can't be spacious?<br/></p>';
如您所见,circle_2在字符串中有一个撇号,因此它会破坏脚本:
Uncaught SyntaxError: Unexpected token ILLEGAL
我将使用什么过滤器来解决这个问题(PHP或JavaScript)?
解决方法:
使用PHP,您可以尝试:
<?php echo str_replace("'", "\'",$c);