0

I heard lot of experts saying entering php code inside javascript is not a good practice. I wanted to know if it's true. If yes, then will it effect the performance? or is there any other reasons?

For example:

<?php
$num=1;
?>

<script>
var x = "<?php echo $num;?>";
</script>
4

6 回答 6

2

No, it is not good practice.

will it effect the performance?

I do not specifically know which performance you meant when you wrote that line, but about all performances I can imagine, I would say: Most certainly, no.

is there any other reasons?

Mixing two languages is hard as it requires proper encoding. This makes things complex. Complexity is bad practice.

于 2013-09-10T06:08:51.780 回答
1

Typically, it is bad practice to use language X to generate code in language Y.

Try decoupling the two languages by making data their only interface -- don't mingle the code.

In your example, you could improve the code by using PHP to populate a cfg structure that's available to JavaScript:

https://softwareengineering.stackexchange.com/questions/126671/is-it-considered-bad-practice-to-have-php-in-your-javascript

于 2013-09-10T06:08:24.067 回答
1

NO it will not effect the performance, but it affects manageability and security.

In your case, can your javascript function without knowing the value of num? or Are you just developing the JS script from PHP? Latter is the use you should avoid.

Lets take an example where num was used to know the number of items in shopping cart. Now thats a very vital piece of information, but since its JS, it can easily be manipulated. In such case, you should store such sensitive information on the server and not on the client.

于 2013-09-10T06:14:08.217 回答
0

A few points:

  1. You lose the ability to minify your JS scripts because it depends on PHP output
  2. Code quickly gets difficult to maintain. You will need to scan through PHP tags in your javascript code.

Normally, I declare a global config object and pull it through a separate ajax request when the page loads (This can be a PHP script echoing JSON).

MyApp : {
   x: '123',
   y: 'xxx'
}

and then access it from my javascript files later:

(function(){
   alert(MyApp.x)
})();
于 2013-09-10T06:14:58.457 回答
0

I dont think this a bad practice, if the values are dynamic, you can just do as,

test.php

<script type="text/javascript">
    var foo = '<?php echo $foo;?>';
</script>
<script type="text/javascript" src="test.js"></script>

test.js

$(function(){
    alert(foo);
});

If it is not dynamic values, recommends no need to use php tags

于 2013-09-10T06:17:13.370 回答
0

I don't think it is that bad. Assign your dynamic PHP values to a JavaScript variable in your PHP templates(as first line if possible) and then call these variables inside your external JavaScript files. And I fully agree with @hakre answer.

于 2013-09-10T06:20:40.527 回答