2017-03-05 29 views
1

問題:我的腳本src標記在我的index.html頁面中,但在瀏覽器上,此腳本未加載(實際上它加載但看起來像index.html文件0_0看下面的圖片)。問題是:我如何使用html代碼中的不同文件(myscripts.js)中的JavaScript代碼?轉到如何在我的html頁面上使用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頁面並使用腳本/文件夾中的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> 
+0

rofl,「http.ServeFile(w,r,r.URL.Path [1:])」 - 記憶中,作爲白癡代碼的一個例子。小,你一定會陷入困境。示例我的代碼:https://github.com/spouk/spoukfw/blob/master/spoukrender.go – Spouk

回答

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目錄。

Here也是使用這種技術的教程。

+0

對此+1,從不使用r.URL.Path [1:]作爲問題 - 您允許用戶輸入以直接選擇文件系統上的路徑。 –

+0

我是否正確理解StaticFiles應該替換爲ScriptsDirectory? 所以,我可以使用模板,並顯示與JavaScript裏面的HTML頁面,如: '' 或者我可以使用FileServer提供文件但不是模板? 我可以以兩種方式使用嗎?像HTML和文件服務器的模板只有一個目錄「腳本」? – Illia

+0

@Illia謝謝你的收穫。編輯。 Golang提供了自己的誘人引擎,你可以閱讀[這裏](https://golang.org/pkg/text/template/) – weqlix

相關問題