1

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

2
  • The Go code looks OK, so your issue is likely in the client-side code, which wasn't listed. Commented Apr 25, 2017 at 20:49
  • Are you sure the first output string is from that very endpoint? Show the network tab screenshot and your corresponding js code. Commented Apr 25, 2017 at 20:54

1 Answer 1

3

You need to additionally check the req.readyState:

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

References:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.