英文:
Go How can I use JavaScript code on my html page
问题
问题:我在我的index.html页面中有一个script src标签,但在浏览器中这个脚本不加载(实际上它加载了,但看起来像是index.html文件0_0,请参见下面的图片)。问题是:我如何在我的html页面上使用不同文件(myscripts.js)中的JavaScript代码?
在搜索过程中,我找到了一个“解决方案”,但它并没有完全按照应该的方式工作。我只是在viewHandler方法中添加了这一行代码:
http.ServeFile(w, r, r.URL.Path[1:])
在此之后,项目的外观变成了这样:
总结一下:
我的目标是显示html页面并使用位于scripts/文件夹中的JavaScript函数。
项目结构:
-scripts
--myscripts.js
-templates
--index.html
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:
function clickFunc(){
console.log("clicked")
}
index.html:
<head>
<script type="text/javascript" src="scripts/myscripts.js"></script>
</head>
<body>
<button onclick="clickFunc()">Click me</button>
</body>
</html>
英文:
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 ). The question is: How can I use JavaScript code which is in different file ( myscripts.js ) on my html page ?
js file looks like html ( index.html ) file
During googling I found "solution" but I does not work completely like it should. I just added this line to viewHandler method :
http.ServeFile(w, r, r.URL.Path[1:])
After this, project started look like this:
index.html after adding line above
To sum up:
My goal is to show html page and use javascript function which are in scripts/ folder.
Project Structure :
-scripts
--myscripts.js
-templates
--index.html
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:
function clickFunc(){
console.log("clicked")
}
index.html:
<html>
<head>
<script type="text/javascript" src="scripts/myscripts.js"></script>
</head>
<body>
<button onclick="clickFunc()">Click me</button>
</body>
</html>
答案1
得分: 2
你可以使用http
包从特定目录提供静态文件。
例如:
func main() {
ScriptsDirectory := http.FileServer(http.Dir("scripts"))
http.Handle("/scripts", ScriptsDirectory)
log.Println("Listening at port 3000")
http.ListenAndServe(":3000", nil)
}
这样可以直接从该目录提供文件。
然后,你可以在你的index.html页面中直接引用/scripts
目录。
这里还有一个使用这种技术的教程。
英文:
You should be able to serve static files from a specific directory using the http
package.
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.
Here is also a tutorial where this technique is used.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论