我有一个php页面,当用户将产品添加到购物车时,我会在其中显示jQuery警报。警报中显示的消息是来自php页面的变量,其中存储了所有语言元素。
$cartaddeditem='The product was added to your cart.\r\n You can view your <a href=\'cart.php?action=show\'>shopping cart</a> or click OK to continue shopping';
然后,在页面上:
<body onload="jAlert('success', '<?=$cartaddeditem?>', '<?=$minicart?>');" <? } >
问题是由于$ cartaddeditem var中的引号导致警报无法触发,我在firebug中收到错误消息:
Error: missing ) after argument list
Line: 1, Column: 22
Source Code:
jAlert('success', The product was added to your cart.\r\n You can view your <a href=\
如何在jQuery的消息字符串中转义引号?我尝试了几种具有双引号和单引号的转义类型,一个或两个反斜杠但没有任何效果。
答案 0 :(得分:3)
尝试使用双引号引用HTML属性。
$cartaddeditem = 'The product was added to your cart.\r\n You can view your <a href="cart.php?action=show">shopping cart</a> or click OK to continue shopping';
我还建议您不要添加onload
属性并改用$(document).ready(
吗?
$(function(){
jAlert('success', '<?=$cartaddeditem?>', '<?=$minicart?>');
});
<强>更新强>:
您还可以使用json_encode
确保引号不会发生冲突。 json_encode
也适用于字符串,它输出一个由双引号括起来的字符串(所以不要在参数周围添加引号)。
$(function(){
jAlert('success', <?=json_encode($cartaddeditem)?>, <?=json_encode($minicart)?>);
});
答案 1 :(得分:2)
正确转义PHP输出:
<body onload="jAlert('success',
<?php echo json_encode($cartaddeditem); ?>,
<?php echo json_encode($minicart); ?>);" <? } >
<强>更新强>
因为它是在tag属性中写的,所以双引号不起作用(感谢Rocket)!
所以你要么希望addslashes
足够了:
<body onload="jAlert('success',
'<?php echo addslashes($cartaddeditem); ?>',
'<?php echo addslashes($minicart); ?>');" <? } >
或者你做了Rocket在答案中描述的内容。
更新2
顺便说一句,您应该将PHP字符串更改为双引号,以便\r\n
被评估为换行符:
$cartaddeditem = "The product was added to your cart.\r\n You can view your <a href='cart.php?action=show'>shopping cart</a> or click OK to continue shopping";