admin管理员组文章数量:1400036
<?php
/* ... Getting record from database */
$ment = $record["ment"];
/* There might be quotes or double quotes, we don't know */
echo "<input type='button' onclick=\"doSomething('$ment')\" />";
?>
<script>
function doSomething(ment) {
alert(ment);
/* Something else */
}
</script>
When $ment string contains a single quote , I'm getting "Uncaught SyntaxError: Unexpected token ILLEGAL" error in javascript.
- I add slashes before quotes, it didn't work -
$ment = str_replace("'","\'",$ment);
How can I escape quote and double quote in this example?
<?php
/* ... Getting record from database */
$ment = $record["ment"];
/* There might be quotes or double quotes, we don't know */
echo "<input type='button' onclick=\"doSomething('$ment')\" />";
?>
<script>
function doSomething(ment) {
alert(ment);
/* Something else */
}
</script>
When $ment string contains a single quote , I'm getting "Uncaught SyntaxError: Unexpected token ILLEGAL" error in javascript.
- I add slashes before quotes, it didn't work -
$ment = str_replace("'","\'",$ment);
How can I escape quote and double quote in this example?
Share Improve this question edited May 4, 2015 at 21:00 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Nov 3, 2011 at 20:08 Okan KocyigitOkan Kocyigit 13.5k18 gold badges72 silver badges131 bronze badges 2- Not relevant with the php error but You're missing closing '>' of <input tag – Birey Commented Nov 3, 2011 at 20:11
- @Birey,@Bakudan sorry i didn't copy the code, write it here, and missed the "/>" tag and a double quote. now I edited it. – Okan Kocyigit Commented Nov 3, 2011 at 20:19
3 Answers
Reset to default 9Use json_encode(), which guarantees your output will be syntactically valid JavaScript code:
<input type="button" onclick="doSomething(<?php echo json_encode($ment) ?>">
Use the PHP function addslashes().
You can try something like this in 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;
}
Hope this help :)
本文标签: Escaping quote in JavaScript and PHPStack Overflow
版权声明:本文标题:Escaping quote in JavaScript and PHP - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744222400a2595931.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论