Vue+Golang简单的表单提交

用Vue.js+Golang实现的简单表单提交数据到后台,并成功跳转到前台。

1,项目结构
Vue+Golang简单的表单提交_第1张图片
2,html代码


<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>helloform_Vuetitle>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script src="/static/vue.js">script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]">script>
    head>
    <body>
    <div class="hello">
        <ul>
            <form @submit.prevent="submit">
                <input type="text" name="name" v-model="user.username">
                <input type="password" name="password" v-model="user.password">
                <input type="submit" value="提交">
            form>
        ul>
    div>
    <script>
        var vm = new Vue({
         el: '.hello',
         data: {

            user: {
                username: '',
                password: ''
            }
            },

            methods: {
                 submit: function(event) {
                    var qs = JSON.stringify(this.user);
                    this.$http.post('/login', qs).then((response) => {
                        // success callback
                        alert("success");
                    }, (response) => {
                        // error callback
                        alert("error")
                    });

                }
            },
        })
    script>

    body>
html>

3,go代码

package main

import (
    "encoding/json"
    "fmt"
    "html/template"
    "io/ioutil"
    "log"
    "net/http"
    _ "strings"
)

func login(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    fmt.Println("method:", r.Method) //获取请求的方法
    if r.Method == "GET" {
        t, _ := template.ParseFiles("helloword.html")
        log.Println(t.Execute(w, nil))
    } else {
        defer r.Body.Close()
        con, _ := ioutil.ReadAll(r.Body) //获取post的数据
        fmt.Println(string(con))

        var dat map[string]interface{}
        if err := json.Unmarshal([]byte(string(con)), &dat); err == nil {
            fmt.Println(dat)
            fmt.Println(dat["username"])
        } else {
            fmt.Println(err)
        }

        /*
            //请求的是登录数据,那么执行登录的逻辑判断
            fmt.Println("username:", r.Form["username"])
            fmt.Println("password:", r.Form["password"])*/
    }
}

func main() {
    h := http.FileServer(http.Dir("static"))
    http.Handle("/static/", http.StripPrefix("/static/", h)) // 启动静态文件服务
    http.HandleFunc("/login", login)                         //设置访问的路由
    err := http.ListenAndServe(":9077", nil)                 //设置监听的端口

    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}



源码下载github Vue+Golang简单的表单提交,Star下吧

你可能感兴趣的:(golang,vue.js)