最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - what does it mean when we echo javascript - Stack Overflow

programmeradmin1浏览0评论

I am not able to figure out what we really mean when we echo javascript. Does it mean; the function inside script will execute inevitably? I mean, will it execute with out even being called? I've seen long scripts that seem to include a plete page inside an echo statement.

echo "<script type='text/javascript'>
$(function(){
blah blah blah
});
</script>";

I am not able to figure out what we really mean when we echo javascript. Does it mean; the function inside script will execute inevitably? I mean, will it execute with out even being called? I've seen long scripts that seem to include a plete page inside an echo statement.

echo "<script type='text/javascript'>
$(function(){
blah blah blah
});
</script>";
Share Improve this question edited Mar 18, 2012 at 18:48 vascowhite 18.4k9 gold badges63 silver badges78 bronze badges asked Mar 18, 2012 at 18:44 harryharry 2204 silver badges15 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 9

It means exactly the same thing as when we echo HTML: that text will be sent to the browser. What the browser does with it is independent of what PHP does.

echo is how you print output in PHP, it doesn't do anything special otherwise.

You can often see examples like yours in poorly organized, messy code. Like you say:

I've seen long scripts that seem to include a plete page inside an echo statement.

People get into a bad habit of "echoing" everything, rather than, in your case, using an external javascript file, or learning to break into or out of a PHP block for view logic.

<p>This is a variable: <?php echo $var; ?></p>

Usually should be preferred to:

echo "<p>This is a variable: $var</p>";

In general, you should avoid mixing HTML, CSS, and JavaScript into your PHP code unless it's in a template or view file. Just remember there are a lot of inexperienced coders out there and you shouldn't imitate everything you see.

It's better to inject PHP into your HTML, not the other way around.

With your given statement,

 echo "<script type='text/javascript'>
      $(function(){
      blah blah blah
      });
      </script>"; // You had a non useful " above

The output on the page will only be:

 <script type='text/javascript'>
      $(function(){
      blah blah blah
      });
      </script>

It won't execute the function.

$(function() {}) is a shotcut to $(document).ready(function() { })

The content of this function will be executed when the DOM is ready (a little bit before the page is pletely loaded)

发布评论

评论列表(0)

  1. 暂无评论