简体   繁体   中英

perl, javascript - how to backescape any special characters printing in perl into javascript

how can i backescape any special characters in perl that i'm printing for javascript coding (ie $asdf, $asdf1, $asdf2, $asdf3, $KEY_ID)?

if ($USER_GROUPS_OKAY == 1)
{
    print qq|
    <script>
        var params = \$("#USER_INPUT_FORM").serializeArray();
        params.push({ name: 'menu_mode', value: 'VIEW_IV' });
        params.push({ name: 'KEY_ID_VALID', value: '$KEY_ID' });
        params.push({ name: 'SOURCE_P_NAME', value: '$asdf' });
        params.push({ name: 'DESTINATION_P_NAME', value: '$asdf1' });
        params.push({ name: 'SOURCE_D_NAME', value: '$asdf2' });
        params.push({ name: 'DESTINATION_D_NAME', value: '$asdf3' });                     
        \$.get("cgi_scripts/$0",params,function(data){\$("#graphs").html(data)});
    </script>
|;
}

Note: $asdf, $asdf1, $asdf2, $asdf3 are perl variables - if $asdf is defined = qq|'helo world % &%^&*^ '|, this might kill the code

You'll never catch everything without rewriting the JSON encoder. See encode_json in JSON (from CPAN).

Inside a double quote (ie " or qq ) you can escape with a slash \ however if that is getting confusing because of other meanings/uses of the slash I would recommend changing the parts of the statement that do not need interpolation into single-quote strings (ie ' or q ) and join them with the string cat operator "dot" ( . ).

If I read you correctly, the only Perl-side variable you need is $0 , correct? Further the escaped single dollars are only for Perl's sake so we can remove them inside the single-quotes.

if ($USER_GROUPS_OKAY == 1)
{
    print q|
      <script>
        var params = $("#USER_INPUT_FORM").serializeArray();
        params.push({ name: 'menu_mode', value: 'VIEW_IV' });
        params.push({ name: 'KEY_ID_VALID', value: '$KEY_ID' });
        params.push({ name: 'SOURCE_P_NAME', value: '$asdf' });
        params.push({ name: 'DESTINATION_P_NAME', value: '$asdf1' });
        params.push({ name: 'SOURCE_D_NAME', value: '$asdf2' });
        params.push({ name: 'DESTINATION_D_NAME', value: '$asdf3' });                     
        $.get(
    | . qq|
        "cgi_scripts/$0"
    | . q|
        ,params,function(data){$("#graphs").html(data)});
      </script>
    |;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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