Category Archives: ajax

ajax golang

app.yaml

application: ajax-test
version: 1
runtime: go
api_version: go1.8

handlers:
- url: /html
  static_dir: static/html
- url: /js
  static_dir: static/js
- url: /.*
  script: _go_app

main.go

package app

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

func init() {
    http.HandleFunc("/", handler)
    http.HandleFunc("/ajax", ajaxHandler)
    http.HandleFunc("/hello", helloHandler)
}

func handler(w http.ResponseWriter, r *http.Request) {
    t, err := template.New("template").ParseFiles("index.tmpl")
    if err != nil {
        log.Print("error", err)
    }
    t.ExecuteTemplate(w, "index", nil)
}

func ajaxHandler(w http.ResponseWriter, r *http.Request) {
    log.Print(r.URL.RawQuery)
    fmt.Fprintf(w, "Hello, ajax!")
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World")
}

index.tmpl

{{define "index"}}
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</head>
<body>
<div class="container">
  <select>
    <option value=""></option>
    <option value="1">one</option>
    <option value="2">two</option>
  </select>
  <div id="ajax"></div>
</div>
</body>
</html>
{{end}}

static/html/ajax.html

<p>ajax!</p>

static/js/app.js

$(function() {
  $('select').change(function() {
    $.ajax({
        url: "ajax",
        type: 'GET',
        data: {val:"test"},
        timeout: 10000,
        dataType: 'html'
    }).done(function (data) {
      $('#ajax').html(data)
    }).fail(function (data) {
    }).always(function (data) {
   });
  })
});