samadadi
samadadi

Reputation: 3370

Golang - multiple response values in web app

I write simple go web app. In this app, i am sending ajax post request and returning simple "hello world!" string and print it in console, but something is strange. There is three response value in console output. One with empty value and two response with "hello world!" string values. What is wrong with my code?

Golang Code:

package main

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

func main() {
     http.HandleFunc("/ajax", ajaxHandler)
     http.HandleFunc("/script.js", srcHandler)
     http.HandleFunc("/", mainHandler)
     http.ListenAndServe(":8080", nil)
}

func mainHandler(w http.ResponseWriter, r *http.Request) {
    t, err := template.ParseFiles("home.html")
    if err != nil {
        http.Error(w, http.StatusText(500), 500)
        return
    }

    err = t.Execute(w, nil)
    if err != nil {
        http.Error(w, http.StatusText(500), 500)
        return
    }
}

func srcHandler(w http.ResponseWriter, r *http.Request) {
     http.ServeFile(w, r, "script.js")
}

func ajaxHandler(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Hello World!")
}

Javascript Code:

(function () {
    window.onclick = function () {
        var req = new XMLHttpRequest();
        req.open("post", "/ajax", true);
        req.send();

        req.onreadystatechange = function () {
            console.log(req.responseText);
       }
   };
}());

enter image description here enter image description here

Upvotes: 1

Views: 543

Answers (1)

zerkms
zerkms

Reputation: 254916

You need to additionally check the req.readyState:

   req.onreadystatechange = function () {
        if (req.readyState === XMLHttpRequest.DONE) {
            console.log(req.responseText);
        }
   }

References:

Upvotes: 3

Related Questions