简体   繁体   中英

Why does Javascript alert pops up only numbers and not strings?

Can anyone help me understanding why:

<?php $x = 'b'; ?>
<script> var v=<?php echo $x;?>;  alert(v);</script>

does not pop up an alert whereas

<?php $x = '3'; ?>
<script> var v=<?php echo $x;?>;  alert(v);</script>

does pop up an alert with the text 3?

You're echoing a single letter b into your script element, which results in:

<script> var v=b;  alert(v);</script>

This is an identifier as far as JavaScript is concerned, not a string. Since the JavaScript variable b isn't defined, an error occurs, and nothing is alerted.

When you echo a 3:

<script> var v=3;  alert(v);</script>

What JavaScript sees is a number literal 3, which it has no problem assigning and alerting.

Always look at the rendered output.

<script> var v = 3; alert(v); </script>

vs.

<script> var v = b; alert(v); </script>

To reliably pass a PHP variable into JavaScript, use json_encode

Try:

<?php $x = '3'; ?>
<script> var v='<?php echo $x;?>';  alert(v);</script>

Basically PHP code runs at the server side before the page loads and Javascript starts executing after the script in the page loads.

So as per your code

<?php $x = 'b'; ?>
<script> var v=<?php echo $x;?>;  alert(v);</script>

When that code is resolved at the server side , the php values would have been filled in the script tags.

it will be like

<script> var v=b;  alert(v);</script>

Now when the page is rendered at the client. Once this line is executed, javascript starts looking at the variable b. In terms of PHP it was a string but in terms of javascript its a variable as it's not enclosed by double quotes.

As javascript doesn't find any variable named b , it throws b is undefined error.

Now when it comes to number:

<?php $x = '3'; ?>
<script> var v=<?php echo $x;?>;  alert(v);</script>

In the client this will be rendered as

<script> var v=3;  alert(v);</script>

Now as it's just a number and not a variable. Javascript doesn't throw any error.

if you want the string to work in javascript then,

add quotes for b inside the php variable

    <?php $x = '"b"'; ?>
    <script> var v=<?php echo $x;?>;  alert(v);</script>

Now even PHP strings will give alert

Your generated javscript is lacking the enclosing quotes or the literal value. therefore the assignment var v=... runs into an error unless the assigned value is a number.

use

<script> var v="<?php echo $x;?>";  alert(v);</script>

instead to see all output (but beware of double quotes in $x ).

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