简体   繁体   English

问题包括 php 中的外部 js 脚本

[英]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:并使用以下 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:我认为我可以做的是,而不是在每个页面的<head>中使用相同的脚本,而是将脚本放在 external.js 文件中并使用:

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

now my root is.../ece70141/现在我的根是.../ece70141/

I have just put it in the same directory (.js file as the others) just to get it to work.我只是将它放在同一个目录(与其他文件相同的 .js 文件)中,只是为了让它工作。 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())?>您必须通过 PHP 提供 JavaScript 文件,否则<? print date("F d, YH:i:s", time())?> <? print date("F d, YH:i:s", time())?> will not be parsed. <? print date("F d, YH:i:s", time())?>不会被解析。

It might be as simple as setting .php as file suffix (instead of .js ) and adding它可能就像将.php设置为文件后缀(而不是.js )并添加一样简单

<?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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM