简体   繁体   中英

issue including external js scripts in php

so please take into account I am a newbie. I currently use the following script throughout my pages to display the time:

var currenttime = '<? print date("F d, Y H:i:s", time())?>' //PHP method of getting server date
    var montharray=new Array("January","February","March","April","May","June","July","August","September","October","November","December")
    var serverdate=new Date(currenttime)

    function padlength(what){
    var output=(what.toString().length==1)? "0"+what : what
    return output
    }

    function displaytime(){
    serverdate.setSeconds(serverdate.getSeconds()+1)
    var datestring=montharray[serverdate.getMonth()]+" "+padlength(serverdate.getDate())+", "+serverdate.getFullYear()
    var timestring=padlength(serverdate.getHours())+":"+padlength(serverdate.getMinutes())+":"+padlength(serverdate.getSeconds())
    document.getElementById("servertime").innerHTML=datestring+" "+timestring
    }

    window.onload=function(){
    setInterval("displaytime()", 1000)
    }

and display it with the following html:

<div id="header"><span class="time" id="servertime"></span></div>

what I assumed I could do, rather than having the same script in <head> of every page, put the script in an external.js file and include it using:

<script type="text/javascript" src="live_clock.js"></script>

now my root is.../ece70141/

I have just put it in the same directory (.js file as the others) just to get it to work. However its not working. Could somebody please advise me how to do this properly?

many thanks,

You have to serve the JavaScript file through PHP otherwise <? print date("F d, YH:i:s", time())?> <? print date("F d, YH:i:s", time())?> will not be parsed.

It might be as simple as setting .php as file suffix (instead of .js ) and adding

<?php 
    header('Content-type: text/javascript');
    // or  header('Content-type: application/javascript');
?>

at the top.

I'd say you should do something like this:

<script>
     var currenttime = '<?php echo date("F d, Y H:i:s", time()); ?>'
</script>
<script src="/your/path/to/the/javascript.js"></script>

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