[英]how to include javascript inside html
Sorry for asking this silly question.抱歉问了这个愚蠢的问题。
I got stuck to include a javascript file in my html page in a php project.我被困在php项目的html页面中包含一个javascript文件。 when I try this it works fine-当我尝试这个时它工作正常 -
<script type="text/javascript" src="script.js"></script>
But when I want to load the script.js file from my js directory it does not work.但是当我想从我的js目录加载script.js文件时,它不起作用。 I tried-我试过了-
<script type="text/javascript" src="js/script.js"></script>
NB: I have my js folder in the same myproject directory alongside my index.php and script.js is located inside the js folder.注意:我的js文件夹与我的index.php和script.js位于js文件夹内的同一个myproject目录中。
Since there are subfolders in your project, to have js/script.js working you have to set your base path in your index.php like由于您的项目中有子文件夹,要让 js/script.js 正常工作,您必须在 index.php 中设置基本路径,例如
echo '<base href="http://localhost/myproject/">';
then the following line as a normal html然后以下行作为正常的 html
<script type="text/javascript" src="js/script.js"></script>
You can't.你不能。 PHP doesn't execute Javascript code. PHP 不执行 Javascript 代码。 Since Javascript and PHP are both scripting languages.由于 Javascript 和 PHP 都是脚本语言。 You can use Jquery or AJAX or something like this to run js code您可以使用 Jquery 或 AJAX 或类似的东西来运行 js 代码
<script> var my_javascript_var = "<?php echo 'some value I need on the client side'; ?>"; alert (my_javascript_var ); </script>
It might be access denied reading js folder or..anything really.读取 js 文件夹或..任何东西都可能被拒绝访问。 ...but the best you can do - open developer tools in your browser (hit F12 on Chrome), go to tab "Network" and refresh the page - you should see the reason why it doesnt load- status code will tell you. ...但是您可以做的最好的事情-在浏览器中打开开发人员工具(在 Chrome 上按 F12),go 到“网络”选项卡并刷新页面-您应该会看到它不加载的原因-状态代码会告诉您。
Found out that I was calling my script in <head>
tag of html which did not work for me.发现我在 html 的<head>
标记中调用我的脚本,这对我不起作用。 But calling it before closing of <body>
tag worked!但是在<body>
标签关闭之前调用它有效!
Don't know why.不知道为什么。 Can anyone explain?谁能解释一下?
And obviously thanks everyone.显然感谢大家。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.