Go 如何在我的 html 页面上使用 JavaScript 代码

标签 go

问题:我的 index.html 页面中有 script src 标记,但在浏览器上该脚本未加载(实际上它加载但看起来像 index.html 文件 0_0,请参见下图)。问题是:如何在我的 html 页面上使用不同文件 (myscripts.js) 中的 JavaScript 代码?

js file looks like html ( index.html ) file

在谷歌搜索期间,我找到了“解决方案”,但我并没有完全按照它应该的方式工作。我刚刚将这一行添加到 viewHandler 方法中:

http.ServeFile(w, r, r.URL.Path[1:])

在此之后,项目开始是这样的:

index.html after adding line above

总结:

我的目标是显示 html 页面并使用 scripts/文件夹中的 javascript 函数。

项目结构:

-scripts 
 --myscripts.js
-templates
 --index.html
server.go

服务器.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>

最佳答案

您应该能够使用 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 目录。

Here也是使用此技术的教程。

关于Go 如何在我的 html 页面上使用 JavaScript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42612662/

相关文章:

xml - Golang xml.Unmarshal 任意元素

pointers - 定义结构时何时使用指针

reflection - 无需编译即可检查变量实现接口(interface)

go - 使用 golang 客户端从远程 kubernetes 命令流输出

php - 迭代从 PHP 序列化格式解码的 map

go - 从带有锁的 map 中读取不会通过 channel 返回值

go - 将整数放入缓冲区并用零填充左边?

go - 存储和检索接口(interface)的字节表示

mongodb - 如何使用 mongo-go-driver 运行 mongo 命令?

python - golang gdb - 打印变量