Beginner help with basic go http server with jquery

Hi, there. I have a very basic page (small learning project) that is using some jQuery/html to dynamically load some pages and it works when the static files are opened in the browser, but not on my local Go web server. When you open index.html in a browser everything works and when you clink on links the pages are instantly loaded, but when I run this locally with main.go it loads the index 2 times. I am doing something fundamentally wrong here, but I can’t figure it out. After numerous attempts and google searches I have given up. Sorry if anything it is a bit vague. Any support would be greatly appreciated. Thanks in advance for your support.

This is how it should look:
image
This is how it looks when ran with main.go http server:
(Sorry, for someone reason this forum tells me that I can only upload 1 picture)
Basically it repeats the Home About Contact 2x.

main.go:

package main

import (
	"log"
	"net/http"
)

func index(res http.ResponseWriter, req *http.Request) {
	http.ServeFile(res, req, "index.html")

}

func main() {

	log.Println("Listening...")

	http.HandleFunc("/", index)
	http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("js"))))
	// Start the HTTP server
	http.ListenAndServe(":8085", nil)

}

Index.html:

<!DOCTYPE html>
<html>
    <head>
        <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
    </head>
    <body>
            
        <a href="home.html">Home</a>
        <a href="about.html">About</a>
        <a href="contact.html">Contact</a>

        <div id="content"></div>
        <script src='js/loader.js'></script>
        
    </body>
</html>

loader.js (the part, which is instantly changing the html page with jQuery):

$(document).ready(function(){
    $("#content").load("home.html")
});

$('a').click(function(){
    var page = $(this).attr('href');
    $("#content").load(page);
//alert(page);
    return false;
});

about.html

This is the about Page

contact.html

This is the contact Page

home.html

This is the home Page

Thanks for taking the time to support. I really like Go, but still learning.

I think I have found the reason for this. Apparently it has to do with Go handler responding too fast before the javascript can dynamically load the html. I am new to web development so this was new for me. If I find the exact solution I will post it, but the problem appears to be with the js.

At first sight seems you request a page when you click the link and next $( document ).ready reload the home page. In fact i don’t think you need jquery.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.