简体   繁体   中英

passing php encrypted value into javascript parameter

<script>   
function dinner(x,y)
{
  alert(x,y);
}
</script>
<?php
$x='o7Y2RUgB3wuKsY4QshuARu/Egj4eQBndOoEj70B3GxQ=';  
$y='12.30'
?>
<a onclick="dinner( <?php echo $x;?>,<?php echo $y;?>);" href="#" style="text-    decoration: none;">click me</a>

I am trying to pass encrypted php value(x) into a Javascript function. But I can't get any value in javascript function. I can't understand what is the error?

您应该添加引号:

<a onclick="dinner( '<?php echo $x;?>', '<?php echo $y;?>');" href="#" style="text-decoration: none;">click me</a>

I have updated your code:

   <script>   
     function dinner(x,y)
     {
      alert(x + "" + y);
     }
    </script>
    <?php
    $x='o7Y2RUgB3wuKsY4QshuARu/Egj4eQBndOoEj70B3GxQ=';  
    $y='12.30'?>
    <a onclick="dinner( '<?php echo $x;?>','<?php echo $y;?>');" href="#" style="text-    decoration: none;">click me</a>

Keep in mind that you are passing strings to the javascript function, so you should place the strings between quotes.

The problem is that when the php script compiles, it sends this

<a onclick="dinner( o7Y2RUgB3wuKsY4QshuARu/Egj4eQBndOoEj70B3GxQ=,12.30);" href="#" style="text- decoration: none;">click me</a>

And then browser tries to use variable named o7Y2RUgB3wuKsY4QshuARu/Egj4eQBndOoEj70B3GxQ= and obviously fails.

To fix this issue you have to enclose your echo 's with quotes like this

dinner( '<?php echo $x;?>','<?php echo $y;?>');

Don't forget to check browser console, there is always useful info.

This would be a good way, taking care of all necessary escaping:

$clickHandler = sprintf(
  'return dinner(%s, %s)', 
  json_encode($x), 
  json_encode($y)
);

?>
<a href="#" onclick="<?php echo htmlspecialchars($clickHandler, ENT_QUOTES, 'UTF-8'); ?>" style="text-decoration:none;">click me</a>

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