简体   繁体   English

如何在javascript中转义html /特殊字符串

[英]how to escape html / special strings in javascript

I have a php / javascript scrip which needs to print some text. 我有一个php / javascript脚本需要打印一些文本。 unfortunately it seems that the js breaks down if the string has special characters such 不幸的是,如果字符串具有特殊字符,则js会崩溃

'

Below is a snippet from the script. 以下是脚本的片段。 $messageContent and $subject are the strings with html tags. $ messageContent和$ subject是带有html标签的字符串。 (actually "'" characters) . (实际上是“'”字符)。

echo ' <script language="javascript"> function SelectRedirect(){ switch(document.getElementById(\'s1\').value) { '; echo ' case "?vrj_name='.$vrj_name.'": window.location="?vrj_name='.$vrj_name.'&messageContent='.$messageContent_vrj.'&from_email='.$from_email.'&email='.$email.'&subject='.$subject.'"; break; '; }

I added a function in php to replace "'" with "\\'" and it works (the js executes successfully ) but I can't get ride of them when I display them in the webpage . 我在php中添加了一个函数,将“'”替换为“\\”,它可以正常运行(js成功执行)但是当我在网页中显示它们时,我无法获取它们。

The best way to do this is to encode the values using json_encode . 执行此操作的最佳方法是使用json_encode对值进行编码。 Here is a simple example: 这是一个简单的例子:

<?php
$name = "Jason's Bakery";

?>
<script>
   var name = <?php echo json_encode($name); ?>;
   DoSomethingWithName(name);
</script>

This can be used for integers, strings, and other values. 这可以用于整数,字符串和其他值。 Keep in mind that it will add quotes as needed, so you need to assemble and encode a "whole value at once". 请记住,它会根据需要添加引号,因此您需要组合并编码“整个值”。 In your example of using the URLs, you need to use the PHP urlencode() function to encode them FIRST, and then pass it through json_encode to convert to a javascript value. 在您使用URL的示例中,您需要使用PHP urlencode()函数对它们进行FIRST编码,然后将其传递给json_encode以转换为javascript值。 And if you are placing that inside of an HTML attribute, like onclick , you need to further pass it through htmlspecialchars(..., ENT_QUOTES) and then place it in double quotes. 如果你将它放在HTML属性中,比如onclick ,你需要进一步传递它通过htmlspecialchars(..., ENT_QUOTES) ,然后将它放在双引号中。

http://php.net/manual/en/function.json-encode.php http://php.net/manual/en/function.json-encode.php

So for example, you need to build a URL in PHP and then use it in javascript... 例如,您需要在PHP中构建一个URL,然后在javascript中使用它...

<?php
$name = "Jason's \"Awesome\" Bakery";
$url = "http://site.com/page.php?name=" . urlencode($name);

?>
<script>
   var name = <?php echo json_encode($name); ?>;
   DoSomethingWithName(name);
</script>

<input type="button" onclick="<?php echo htmlspecialchars('window.location = ' . json_encode($url) . ';', ENT_QUOTES); ?>" value="Click Me" />

Which results in something like this: 结果是这样的:

<script>
   var name = "Jason's \"Awesome\" Bakery";
   DoSomethingWithName(name);
</script>

<input type="button" onclick="window.location = &quot;http:\/\/site.com\/page.php?name=Jason%27s+%22Awesome%22+Bakery&quot;;" value="Click Me" />

Needless to say, you do not want to do without these: 不用说,你不想没有这些:

http://php.net/manual/en/function.json-encode.php http://php.net/manual/en/function.json-encode.php
http://www.php.net/manual/en/function.urlencode.php http://www.php.net/manual/en/function.urlencode.php
http://www.php.net/manual/en/function.htmlspecialchars.php http://www.php.net/manual/en/function.htmlspecialchars.php

Due to respects of readability and future maintainability, I'd like to point out a few things which may help you out. 由于可读性和未来可维护性的考虑,我想指出一些可能对您有帮助的事情。

First, I see you're generating HTML elements in a PHP string. 首先,我看到你在PHP字符串中生成HTML元素。 This isn't inherently bad, but when your string wraps across 2 or more lines, it becomes increasingly difficult to manage. 这本身并不坏,但是当你的字符串包含2行或更多行时,管理变得越来越困难。 Instead, you may want to think about escaping PHP for outputting HTML portions, and re-entering PHP for logical portions. 相反,您可能想要考虑转义PHP以输出HTML部分,并重新输入PHP以用于逻辑部分。 You can escape PHP and enter HTML within if statements, function declarations etc, so there's really no good reason not to. 你可以逃避PHP并在if语句,函数声明等中输入HTML,所以没有充分的理由不这样做。 Look at the following example (this solution also escapes the strings in an appropriate manner where its value can contain single quotes, double quotes or line breaks): 请看下面的示例(此解决方案还以适当的方式转义字符串,其值可以包含单引号,双引号或换行符):

<?php

function urlFriendly($input) {
    return urlencode($input);
}

function jsFriendly($input, $urlFriendly = True) {
    $output = htmlentities($input, ENT_QUOTES);
    // Double quotes in PHP translate "\n" to a newline.
    // Single quotes in PHP keep the literal value.
    $output = str_replace("\r\n", '\n', $output); // Windows support
    $output = str_replace("\n", '\n', $output); // Linux support
    if($urlFriendly) { // Encode for use in URLs
      $output = urlFriendly($output);
    }
    return $output;
}

$vrj_name = 'vrj';
$messageContent_vrj = 'message content';
$from_email = 'from email';
$email = 'email';
$subject = 'subject line';

?>
<script type="text/javascript">
    function SelectRedirect() {
    switch(document.getElementById('s1').value) {
        case '?vrj_name=<?php print jsFriendly($vrj_name);?>':
            var toloc = '?vrj_name=<?php print jsFriendly($vrj_name);?>';
            toloc    += '&messageContent=<?php print jsFriendly($messageContent_vrj);?>'';
            toloc    += '&from_email=<?php print jsFriendly($from_email);?>';
            toloc    += '&email=<?php print jsFriendly($email);?>';
            toloc    += '&subject=<?php print jsFriendly($subject);?>';
            window.location = toloc;
            break;
    }
</script>

just like that 就像那样

$escaped_string = addslashes($unescaped_string);

either before 要么之前

$messageContent = addslashes($messageContent);
$subject = addslashes($subject);

or even inline 甚至内联

echo '
case "?vrj_name='.$vrj_name.'":
window.location="?vrj_name='.$vrj_name.'&messageContent='.addslashes($messageContent).'&from_email='.$from_email.'&email='.$email.'&subject='.addslashes($subject).'";
break;
';

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

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