douzhan5262 2014-07-27 16:21
浏览 36
已采纳

GO:javascript和html MIME错误

I'm trying to load javascript in my GO app, but I got the error:

Resource interpreted as Script but transferred with MIME type text/html:     "http://localhost:4747/twttr.js". localhost/:6
Uncaught SyntaxError: Unexpected token < 

GO:

package main

import (
    "net/http"
    "html/template"
)

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":4747", nil) 
}

func handler(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path == "/twttr.js" {
        http.ServeFile(w, r, "twttr.js")
        return
    } 
    t, _ := template.ParseFiles("home.html", "edit.html")
    t.Execute(w, map[string] string {"Title": "My title", "Body": "Hi this is my body"})
}

In my HTML I have something like this:

<!DOCTYPE html>
<html>
<head>
    <title>twitter!</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript" src="twttr.js"></script>
<head>

<body>
    <h1>Add new tweet</h1>
    <form action="/save/{{.Title}}" method="get">
    <button type="button" value="addtweet" class="addtweet">Add Tweet!</button>
    </form>
    Title is {{.Title}}
    {{template "edit.html" .}}
</body>
</html>

JS:

 $(document).ready(function(){
    $('.addtweet').click(function(){
        alert("Handler for .click() called.");
    });
})

Directory structure:

static/
    home.html
    twttr.js
twttr.go

I'm thinking it's got something to do with how I display the templates / html in the GO app. But I don't know the exact problem. I'm new to GO and programming in general so any guidance is much appreciated!

  • 写回答

1条回答 默认 最新

  • dqssst0144 2014-07-27 16:30
    关注

    If you look at your the result of the JS file load, is it even the expected file? I don't see you handling it, based on the posted code, I would guess not. Unless you haven't posted everything. You seem to be serving the same result for every request, including the JS file.

    For serving files through GO, look at: http://golang.org/pkg/net/http/#ServeFile

    You need to check the URL and handle accordingly. Eg:

    if r.URL.Path == "/twttr.js" {
        http.ServeFile(w, r, "static/twttr.js")
        return
    } 
    
    t, _ := template.ParseFiles("home.html", "edit.html")
    t.Execute(w, map[string] string {"Title": "My title", "Body": "Hi this is my body"}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?