douhuan1908 2017-03-05 19:01
浏览 19
已采纳

转到如何在HTML页面上使用JavaScript代码

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:

<head>
<script type="text/javascript" src="scripts/myscripts.js"></script>
</head>
<body>

<button onclick="clickFunc()">Click me</button>

</body>
</html>
  • 写回答

1条回答 默认 最新

  • dongmaqiu6084 2017-03-05 20:16
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型