[英]Go How can I use JavaScript code on my html page
Problem: I have script src tag in my index.html page but on browser this script doesn't load ( actually it loads but looks like index.html file 0_0 see pictures below ). 问题:我的index.html页面中有脚本src标记,但是在浏览器中此脚本未加载(实际上已加载,但看起来像index.html文件0_0,请参见下图)。 The question is: How can I use JavaScript code which is in different file ( myscripts.js ) on my html page ?
问题是:如何使用html页面上不同文件(myscripts.js)中的JavaScript代码?
js file looks like html ( index.html ) file js文件看起来像html(index.html)文件
During googling I found "solution" but I does not work completely like it should. 在谷歌搜索期间,我找到了“解决方案”,但是我并未完全按照应有的方式工作。 I just added this line to viewHandler method :
我只是将这一行添加到viewHandler方法:
http.ServeFile(w, r, r.URL.Path[1:])
After this, project started look like this: 此后,项目开始如下所示:
index.html after adding line above 在上面添加行之后的index.html
To sum up: 总结一下:
My goal is to show html page and use javascript function which are in scripts/ folder. 我的目标是显示html页面并使用scripts /文件夹中的javascript函数。
Project Structure : 项目结构:
-scripts
--myscripts.js
-templates
--index.html
server.go
Server.go : Server.go:
func viewHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("listening . . .")
tpl.ExecuteTemplate(w, "index.html", nil)
}
func main() {
http.HandleFunc("/", viewHandler)
http.ListenAndServe(":8080", nil)
}
myscripts.js: myscripts.js:
function clickFunc(){
console.log("clicked")
}
index.html: index.html的:
<head>
<script type="text/javascript" src="scripts/myscripts.js"></script>
</head>
<body>
<button onclick="clickFunc()">Click me</button>
</body>
</html>
You should be able to serve static files from a specific directory using the http
package. 您应该能够使用
http
包从特定目录中提供静态文件。
For example: 例如:
func main() {
ScriptsDirectory := http.FileServer(http.Dir("scripts"))
http.Handle("/scripts", ScriptsDirectory)
log.Println("Listening at port 3000")
http.ListenAndServe(":3000", nil)
}
Will let you server the file directly from that directory. 让您直接从该目录中服务器文件。
From there you can reference the /scripts
directory in your index.html page as is. 从那里可以直接在index.html页面中引用
/scripts
目录。
Here is also a tutorial where this technique is used. 这也是使用此技术的教程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.