[英]Escaping quote in JavaScript and PHP
<?php
/* ... Getting record from database */
$comment = $record["comment"];
/* There might be quotes or double quotes, we don't know */
echo "<input type='button' onclick=\"doSomething('$comment')\" />";
?>
<script>
function doSomething(comment) {
alert(comment);
/* Something else */
}
</script>
當$ comment字符串包含單引號時,我在JavaScript中收到“ Uncaught SyntaxError:Unexpected token ILLEGAL ”錯誤。
$comment = str_replace("'","\\'",$comment);
在此示例中,如何轉義引號和雙引號?
使用json_encode() ,以確保您的輸出在語法上是有效的JavaScript代碼:
<input type="button" onclick="doSomething(<?php echo json_encode($comment) ?>">
使用PHP函數addlashes() 。
您可以在Javascript中嘗試類似的方法:
function addslashes(str){
str=str.replace(//g,'\');
str=str.replace(/'/g,''');
str=str.replace(/"/g,'"');
str=str.replace(//g,'');
return str;
}
function stripslashes(str){
str=str.replace(/'/g,''');
str=str.replace(/"/g,'"');
str=str.replace(//g,'');
str=str.replace(/\/g,'');
return str;
}
希望這個幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.