• 【Golang】练习-Web 处理 form 表单请求失败不刷新页面并保存输入的数据


    主函数main.go

    package main
    
    import (
    	"fmt"
    	"html/template"
    	"net/http"
    	"strings"
    )
    
    var UsersDb = make(map[string]*Users)
    
    type Users struct {
    	ID   int
    	Name string
    	Sex  bool
    	Addr string
    }
    
    func NewUser(id int, name string, sex bool, addr string) *Users {
    	return &Users{id, name, sex, addr}
    }
    
    //叠加用户 ID
    func GetId() int {
    	id := 0
    	for _, user := range UsersDb {
    		if user.ID > id {
    			id = user.ID
    		}
    	}
    	return id + 1
    }
    
    //这两个判断用户名是否重复,如果重复返回 true,不重复返回 false
    func filter(user *Users, q string) bool {
    	return strings.Contains(user.Name, q)
    }
    func QueryName(q string) bool {
    	for _, user := range UsersDb {
    		if filter(user, q) {
    			return true
    		}
    	}
    	return false
    }
    
    //添加用户进数据库
    func ModelsAddUser(name string, sex bool, addr string) bool {
    	if !QueryName(name) { //用户不重复执行添加用户数据
    		id := GetId()
    		user := NewUser(id, name, sex, addr)
    		UsersDb[name] = user
    		fmt.Printf("用户【%v】添+成功!!!
    ", name)
    		return true
    	} else { //用户重复则退出
    		fmt.Printf("用户【%v】添+失败!!!
    ", name)
    		return false
    	}
    }
    
    //查看用户,主页,不过我一开始每天夹用户数据,所以看到的用户数据为空
    func GetUsers(w http.ResponseWriter, r *http.Request) {
    	tpl := template.Must(template.ParseFiles("template/user.html"))
    	users := make([]*Users, 0, 10)
    	for _, user := range UsersDb {
    		users = append(users, user)
    	}
    	tpl.ExecuteTemplate(w, "user.html", users)
    }
    
    //增加新用户
    func AddUser(w http.ResponseWriter, r *http.Request) {
    	if r.Method == "GET" {
    		tpl := template.Must(template.ParseFiles("template/create.html"))
    		tpl.ExecuteTemplate(w, "create.html", nil)
    	} else {
    		if ModelsAddUser(
    			r.FormValue("name"),
    			r.FormValue("sex") == "1",
    			r.FormValue("addr"),
    		) {
          //用户添加成功,返回数据到 create.html 的 ajax 进行判断处理
    			fmt.Fprintf(w, `{"result":"sucess"}`)
    
    		} else {
          //用户添加失败,返回数据到 create.html 的 ajax 进行判断处理
    			fmt.Fprintf(w, `{"result":"failed"}`)
    		}
    	}
    }
    
    func Register() {
    	http.HandleFunc("/", GetUsers)
    	http.HandleFunc("/create/", AddUser)
    }
    
    func main() {
    	addr := ":8888"
    	Register()
    	http.ListenAndServe(addr, nil)
    }
    

    html 模板

    user.html

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8" />
            <title>用户管理</title>
        </head>
        <body>
            <a href="/create/">新建</a>  
            <table>
                <thead>
                    <tr>
                        <th>用户</th>
                        <th>性别</th>
                        <th>地址</th>
                    </tr>
                </thead>      
                <tbody>
                    {{ range . }}
                        <tr>
                            <td>{{ .Name }}</td>
                            <td>{{ if .Sex }}男{{ else }}女{{ end }}</td>
                            <td>{{ .Addr }}</td>
                        </tr>
                    {{ end }}
                </tbody>
        </table>
        </body>
    </html>
    

    create.html

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8" />
            <title>新建</title>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
            <script type="text/javascript">
                function insert() {
                    $.ajax({
                        type: "POST",
                        url: "create/" ,
                        data: $('#form1').serialize(),
                        dataType:"json", 
                        success: function (respMsg) {        
                            if (respMsg.result == "sucess") {
                                //获取当前网址,如: http://127.0.0.1:8888/create/
                                var curWwwPath=window.document.location.href;
    
                                //获取主机地址之后的目录,如: create/
                                var pathName=window.document.location.pathname;
                                var pos=curWwwPath.indexOf(pathName);
    
                                //获取主机地址1,如: http://localhost:8888
                                var localhostPaht=curWwwPath.substring(0,pos);
                                //获取主机地址2,如: http://localhost:8888
                                var urlPath = "http://" + window.location.host
                                window.location.assign(urlPath);
                            } else {
                              //弹窗
                                alert("用户名重复!");
                            }
                            
                        },
                        error : function(respMsg) {
                            console.log(respMsg,"error")
                        }
                    });
                }
            </script>
        </head>
        <body>
            <form action="##" method="POST" id="form1" target="postFrame">
                <label>姓名</label><input name="name" value="" /><br/>
                <label>性别</label>
                    <input name="sex" type="radio" value=""  checked="checked"/> 男
                    <input name="sex" type="radio" value=""  /> 女<br/>
                <label>住址</label><textarea name="addr" value=""></textarea><br/>
                <input type="button" value="插入" onclick="insert()">
            </form>       
        </body>
    </html>
    

    执行命令:

    go run main.go
    

    网页演示:

  • 相关阅读:
    Oracle Autonomous Health Framework(AHF)
    Autonomous Health Framework(AHF)相关操作
    Postgresql 正则表达式
    如何去官网下载JDK (JDK8 JDK1.8)
    配置免安装版Oracle客户端
    子用户角色权限菜单 浅谈:子账户设计方案
    EF Power Tools Beta 2 生成 Entity Framework Code First 提示 参数错误 hresult e_invalidarg
    mvc 截取上传图片做头像,自动生成不同小尺寸缩略图
    亚马逊的下拉菜单插件 jQueryMenuAim 使用
    apacheab并发负载压力测试
  • 原文地址:https://www.cnblogs.com/UncleZhao/p/14110076.html
Copyright © 2020-2023  润新知