简体   繁体   中英

Javascript variable not working in php echo

My code :

<?php echo ' <script>var p=0;for(var i=0;i<=5;i++){p++;}alert("ques".p);? >

The value of p is displayed as 0.

You need to close your php tag properly as well as the <script> tag like so:

<?php echo '<script>var p=0;for(var i=0;i<=5;i++){p++;}alert("ques" +p);</script>'; ?>

Also, change the . to a + as you are concatenating in javascript not PHP

正确答案是:

<?php echo '<script>var p=0;for(var i=0;i<=5;i++){p++;}alert("ques" + p)'; ?>

单引号中的字符串将被转义,请改用引号。

<?php echo "<script>var p=0;for(var i=0;i<=5;i++){p++;}alert('ques' +p);</script>"; ?>

The mistakes in your code are,

  1. Close your php tag properly - ?> instead of ? > ?> instead of ? >
  2. Close the script tag in the end - </script>
  3. Close the single quote you started with echo

The correct code would be

<?php echo '<script>var p=0;for(var i=0;i<=5;i++){ p++; } alert("ques" + p); </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