简体   繁体   中英

what is the difference between the following two in javascript?

I am assigning php values to javascript as following

var a = <?php echo 39; ?>

but javascript is throwing following error "Uncaught SyntaxError: Unexpected token ILLEGAL". When I am assigning php values in the following way then I am not getting any problem

var a = "<?php echo 39; ?>";

What I think is php code runs on server side first.So in the first case the php code is executed on server side first then that executed code is sent to the browser.So browser should see that code as(i think)

var a=39;

but instead of that it is throwing error.Why is it happening?

您的第一个示例在javascript变量赋值结束时错过了分号:

var a = <?php echo 39; ?>; //<-- missing semicolon

First of all, it's best practice to always end your statements with a semicolon. But regardless of the discussion in the other answers about where and when you should have one, there is also another very important difference in the two examples you have provided.

Example 1:

var a = <?php echo 39; ?>

Variable a is now an integer (no quotes): http://en.wikipedia.org/wiki/Integer_%28computer_science%29

Example 2:

var a = "<?php echo 39; ?>";

Variable a is now a string (quotes): http://en.wikipedia.org/wiki/String_%28computer_science%29

I would say that the different between variable types is something you should be aware of. Especially in Javascript!

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