简体   繁体   English

为Javascript函数转义HTML的正确方法是什么?

[英]What is a proper way to escape HTML for Javascript function?

I'm getting Uncaught SyntaxError: Unexpected identifier due of the Java-Script clashing syntax or single and double quote. 我收到Uncaught SyntaxError:由于Java脚本冲突的语法或单引号和双引号引起的意外标识符

In the source file,the $str is escaped as special chars but not sure why Javascript will hit error. 在源文件中, $ str被转义为特殊字符,但不确定为什么Javascript会出错。

What is the Correct/Proper way to escape it with single or double quote inside a string for Javascript function use purpose? 为了使用Javascript函数,用字符串内的单引号或双引号将其转义的正确/正确方法是什么?

Below is my code : 下面是我的代码:

<?php
    $str = 'I\'m John Doe < lol > "19" ! ?';
?>
<div onclick="alert('<?php echo htmlspecialchars($str); ?>')">Test</div>
<div onclick="alert(&quot;<?php echo htmlspecialchars($str); ?>&quot;)">Test</div>

The important thing to note here is that you don't just have JavaScript. 这里要注意的重要一点是,您不仅拥有JavaScript。 You have JavaScript in an HTML attribute, so you have to escape for JS then for HTML. HTML属性中包含JavaScript,因此必须先转义JS, 然后转义HTML。

json_encode will escape for JS. json_encode将针对JS进行转义。 It will also add quotes around strings, so do you don't need to do that yourself. 它还会在字符串周围添加引号,因此您不需要自己这样做。

htmlspecialchars will escape for HTML. htmlspecialchars将针对HTML进行转义。

onclick="alert(<?php echo htmlspecialchars( json_encode( $str ) ); ?>"

Any time you're using strings in the context of JavaScript, use JSON-encoding. 每当您在JavaScript上下文中使用字符串时,请使用JSON编码。 JSON is compatible with JavaScript parsers, and all of the escaping needed will be done for you. JSON与JavaScript解析器兼容,并且所有需要的转义都将为您完成。

var str = <?php json_encode($str) ?>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM