代码之家  ›  专栏  ›  技术社区  ›  bobbyh

用引号和换行符对PHP变量进行编码,以传递给javascript函数(然后反转编码)

php
  •  7
  • bobbyh  · 技术社区  · 16 年前

    假设您有一个名为$description的PHP变量,其值如下(包含引号和换行符):

    Tromp L'oeil Sheath Dress
    
    You will certainly "trick the eye" of many in this gorgeous illusion. Add it to your fall wardrobe before it disappears.
    

    您希望将此变量的内容传递给一个javascript函数,该函数将该值写入一个文本类型的输入。

    你会怎么做?我试过这个:

    $description = htmlspecialchars ( $product->description, ENT_QUOTES );
    

    但是,我得到一个JS错误。我也尝试过:

    $description = rawurlencode ( $product->description );
    

    这对值进行编码,如下所示:

    Michael%20Kors%0A%0ATromp%20L%27oeil%20Sheath%20Dress%0A%0AYou%20will%20certainly%20%22trick%20the%20ey%22%20of%20many%20in%20this%20gorgeous%20illusion.%20Add%20it%20to%20your%20fall%20wardrobe%20before%20it%20disappears.%0A%0AAvailable%20in%20Black%2FNude
    

    这个值可以作为一个JS变量传递,但是我不知道有一个JS函数可以清晰地反转php rawurlencode。

    是否有一对匹配的函数可以用来在PHP中对变量进行编码,以便将其传递给JS函数——然后在JS中反转编码,以便获得PHP变量的原始值?

    编辑:为了澄清问题并回复评论,以下是一些测试代码:

    <?php
    $str =<<<EOT
    Tromp L'oeil Sheath Dress
    
    You will certainly "trick the eye" of many in this gorgeous illusion. Add it to your fall wardrobe before it disappears.
    EOT;
    echo 'here is the string: <pre>' . $str . '</pre>';
    ?>
    
    <script type="text/javascript">
    <?php
    // this does not work with JS as i get an unterminated string literal if i just use addslashes in the following commented-out line
    // echo 'alert(\'' . addslashes($str) . '\');';
    
    // this works with JS (the alert activates) but how do i un-rawurlencode in JS?
    // echo 'alert(\'' . rawurlencode($str) . '\');';
    
    // this does not work with JS, because of the line breaks
    echo 'alert(\'' . htmlspecialchars ($str, ENT_QUOTES) . '\');';
    ?>
    </script>
    
    6 回复  |  直到 16 年前
        1
  •  3
  •   ceejayoz    16 年前

    最简单的方法是 json_encode()

        2
  •  2
  •   bobbyh    16 年前

    我在使用这里提出的一些答案时遇到了一些问题,包括换行和解码某些HTML实体的问题,如/。我最终使用rawurlencode(在php中)和decodeuricomponent(在javascript中)作为匹配函数来编码/解码字符串,以便它可以作为JS变量传递。这是其他遇到此问题的人的工作代码。

    <?php
    $str =<<<EOT
    Tromp L'oeil Sheath Dress
    
    You will certainly "trick the eye" of many in this gorgeous illusion. Add it to your fall wardrobe before it disappears.
    Available in Black/Nude
    EOT;
    echo 'here is the string: <pre>' . $str . '</pre>';
    ?>
    <p>below is the variable doc.write'd after being rawurlencod'ed in PHP then decodeURIComponent'ed in JS:</p>
    <script type="text/javascript">
    <?php
    echo 'document.write(decodeURIComponent("'. rawurlencode($str).'"));';
    ?>
    
        3
  •  1
  •   Gumbo    16 年前

    你可以使用 json_encode 如果有的话。它根据 JSON data format 这是javascript的一个子集;因此任何JSON也是有效的javascript。

    <script type="text/javascript">
    <?php
        echo 'alert('. json_encode($str).');';
    ?>
    </script>
    

    否则尝试 PHP’s rawurlencode 然后用解码 JavaScript’s decodeURI :

    <script type="text/javascript">
    <?php
        echo 'alert(decodeURI("'. rawurlencode($str).'"));';
    ?>
    </script>
    
        4
  •  0
  •   Developer    16 年前

    JSON是解决方案。 参见示例代码 两页演示

    首页json.php

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Untitled Document</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    </head>
    
    <body>
    
    
    <script type="text/javascript">
      $(document).ready(function() {
        // This is more like it!
        $('#submit').live('click', function() {
            var id=$("#id").attr("value");
            $.getJSON("json-call.php", {id:id}, function callback(data) {
                $("#list").html("var1:"+data['var1']+"<br/>"+"var2:"+data['var2']+"<br />id:"+data['id']);
            });
        });
    
      });
    </script>
    
    <input id="id" type="text" value="test value" />
    <input type="button" id="submit" value="submit" />
    
    <div id="list"></div>
    
    
    </body>
    </html>
    

    第二页json-call.php

    $var1 = 'your name';
    $var2 = 'your address';
    $id = $_REQUEST['id'];
    print(json_encode(array ('var1' => $var1, 'var2' => $var2, 'id'=>$id)));
    

    结果

    var1:your name
    var2:your address
    id:test value
    
        5
  •  0
  •   NChase    16 年前

    不确定JSON解码是否能满足您的所有需求。htmlspecialchars()和htmlspecialchars_decode()应该为除换行符以外的所有内容提供技巧。换行符有点痛苦,因为换行符和回车符的组合将取决于浏览器,但我认为类似这样的操作应该有效:

    $value = "your string with quotes and newlines in it.";
    
    //take cares of quotes
    $js_value = htmlspecialchars($value);    
    //first line replaces an ASCII newline with a JavaScript newline
    $js_value = str_replace("\n",'\n',$js_value);
    //second line replaces an ASCII carriage return with nothing, so you don't get duplicates
    $js_value = str_replace("\r",'',$js_value);
    
    //reverse to convert it back to PHP
    $php_value = str_replace('\n',"\r\n",$js_value);  
    $php_value = htmlspecialchars_decode($php_value);
    

    也许不是最优雅的解决方案,但那不是我的专长。;)另外,请记住,换行符将像<input type=“text”>字段中的空格一样结束。

        6
  •  0
  •   Echo says Reinstate Monica    16 年前

    这是我做的一件小事:

    function safefor_js($str) {
        return str_replace(array("'",'"',"\n"), array('\x22','\x27','\\n'), $str);
    }
    
    推荐文章