简体   繁体   中英

How Can I execute a PHP function inside a Script tag?

So I have as function for my css that looks like this

function include_css($css="") {
include(SITE_ROOT.DS.'includes'.DS.'stylesheets'.DS.$css);
}

And in the header I use this to call it

<style type="text/css"><?php include_css('public.css'); ?></style>

I would like to do a similar function to call a javascript file to load in ckeditor

function include_javascript($js="") {
include(SITE_ROOT.DS.'includes'.DS.'ckeditor'.DS.$js);
}

But this bit of code doesn't work

<script type="text/javascript"><?php include_javascript('ckeditor.js'); ?></script>

The tool bar doesn't show up when doing it this way. It will show up when I use the website.

<script src="//cdn.ckeditor.com/4.5.11/standard/ckeditor.js"></script>

Why doesn't this work the same way as the Style tag? Since this doesn't work is there a similar way to put PHP into a Script tag?

I put php code inside of script tags frequently for instance to set the initial value of a javascript variable. There is no particular issue with inserting php tags inside of a script tag.

Normally you would load javascript separately to speed page load like this:

<script src="/path-to_js/js-file.js" type="text/javascript"></script>

So something like this should work:

function include_javascript($js="") {
    if ($js)
        echo "<script src=\"/js-path/$js\" type=\"text/javascript\"></script>";
}

If you are trying to embed the javascript code into your html what you are doing ought to work. I noticed that you are setting a default value for your parameter. Make sure that something is actually passed and that the file actually exists. If the result is

<script></script> 

then one of these is most likely the problem.

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