[英]jQuery alerts and escaping quotes
I have a php page on which I show a jQuery alert when a user adds products to their cart. 我有一个php页面,当用户将产品添加到购物车时,在该页面上显示jQuery警报。 The message displayed in the alert is a variable from a php page where all language elements are stored. 警报中显示的消息是来自存储所有语言元素的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';
Then, on the page: 然后,在页面上:
<body onload="jAlert('success', '<?=$cartaddeditem?>', '<?=$minicart?>');" <? } >
The problem is that the alert fails to fire because of the quotes in the $cartaddeditem var and I'm getting an error in firebug that says: 问题是由于$ cartaddeditem var中的引号导致警报无法触发,并且在萤火虫中出现错误,提示:
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=\
How do I escape the quote in the message string for jQuery? 如何转义jQuery消息字符串中的引号? I tried several escaping types with double and single quotes, one or two backslashes but nothing worked. 我尝试了几种带有双引号和单引号,一两个反斜杠的转义类型,但没有任何效果。
Try using double quotes to quote your HTML attributes. 尝试使用双引号将您的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';
May I also suggest not adding onload
attributes and using $(document).ready(
instead? 我还可以建议不要添加onload
属性,而是使用$(document).ready(
吗?
$(function(){
jAlert('success', '<?=$cartaddeditem?>', '<?=$minicart?>');
});
UPDATE : You can also use json_encode
to make sure that quotes don't clash. 更新 :您还可以使用json_encode
来确保引号不会冲突。 json_encode
works on strings too, it outputs aa string surrounded by double quotes (so don't add quotes around the parameter). json_encode
适用于字符串,它输出一个字符串,并用双引号引起来(因此不要在参数周围添加引号)。
$(function(){
jAlert('success', <?=json_encode($cartaddeditem)?>, <?=json_encode($minicart)?>);
});
Properly escape your PHP output: 正确地转义您的PHP输出:
<body onload="jAlert('success',
<?php echo json_encode($cartaddeditem); ?>,
<?php echo json_encode($minicart); ?>);" <? } >
Update 更新资料
Because it's written inside a tag attribute, the double quotes wouldn't work (thanks Rocket)! 因为它是在tag属性中编写的,所以双引号不起作用(感谢Rocket)!
So you'd either have to hope addslashes
is enough: 因此,您要么希望加addslashes
就足够了:
<body onload="jAlert('success',
'<?php echo addslashes($cartaddeditem); ?>',
'<?php echo addslashes($minicart); ?>');" <? } >
Or you do what Rocket described in his answer. 或者您按照火箭在他的回答中描述的做。
Update 2 更新2
Btw, you should change your PHP strings to double quotes so that \\r\\n
gets evaluated as a newline: 顺便说一句,您应该将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";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.