Created
February 28, 2015 05:15
-
-
Save lei-cao/a4004ccab8d528df575b to your computer and use it in GitHub Desktop.
The basic usage of ajax with beego
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"text/template" | |
"github.com/astaxie/beego" | |
) | |
type BeeferController struct { | |
beego.Controller | |
} | |
type User struct { | |
Username string | |
} | |
var tpl string = ` | |
<html> | |
<head> | |
<title>Beefer!</title> | |
</head> | |
<body> | |
<form action=""> | |
<select id="sel"> | |
<option value="1">Dog</option> | |
<option value="2">Tiger</option> | |
<option value="3">Cat</option> | |
</select> | |
You selected: | |
<span id="result"></span> | |
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script> | |
<script type="text/javascript"> | |
(function() { | |
$sel = $("#sel"); | |
$sel.on('change', function() { | |
$.ajax({ | |
type: "POST", | |
url: "/", | |
data: {"sel": $sel.val()} // The data passed to / by POST method | |
}).done(function(msg) { | |
// Render your result | |
$("#result").html(msg.Val); | |
}); | |
}); | |
})(); | |
</script> | |
</body> | |
</html> | |
` | |
func (c *BeeferController) Post() { | |
val := c.GetString("sel") // Get the data "sel" from request | |
// Do your logic | |
result := struct { | |
Val string | |
}{val} | |
c.Data["json"] = &result | |
c.ServeJson() | |
} | |
// The Get method to handle the GET request | |
func (c *BeeferController) Get() { | |
data := make(map[interface{}]interface{}) | |
t := template.New("Beego Template") | |
t = template.Must(t.Parse(tpl)) | |
t.Execute(c.Ctx.ResponseWriter, data) | |
} | |
func main() { | |
beego.Router("/", &BeeferController{}) | |
beego.Run(":8081") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment