Front end: Multiple fields of the form are passed to the back end and saved to the database. (Serialize form content)

The serializeArray() method creates an array of objects (name and value) by serializing form values. 

<script>
    let allData = {}    
    $.each($('form').serializeArray(), function () {
              allData[this.name] = this.value;
          });
          console.log(allData);//全部表单字段,名值对形式:{name: value}
</script>

Pass to the background:

<script>
     $.ajax({
              type:"post",
              url:"/xxxx",
              dataType:"json",
              data:JSON.stringify(allData),
              success: function (res){
                  //do something
              }
          });
</script>

 Receive in the background:

1. Python form

 # 添加公告
    @staticmethod
    def add_notice(request):
        data = {}
        data = json.loads(request.body.decode()) #  将json格式数据转换为字典
        data["notice_id"] = idCreater.appKeyWorker.get_id()
        data["create_time"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print(data)
        Notice.objects.create(**data)
        return JsonResponse({"state": 200, "msg": "success"}, json_dumps_params={'ensure_ascii': False})

 

2. Java form 

 <script>
    var allData = {};
        var t = $('form').serializeArray();
        console.log("t===>",t)
        $.each(t, function () {
            allData[this.name] = this.value;
        });
        console.log(allData);
        $.ajax({
            type:"POST",
            url:"/addUser",
            data:JSON.stringify(allData),
            contentType:'application/json;charset=utf-8',
            dataType:"json",
            success:function (res) {
                // do something
            },
            error:function () {
               // do something
            }
        });
 </script>

 

    @PostMapping("/addUser")
    @Transactional()
    public Object addUser(@RequestBody UsersEntity user){
        Result result = new Result();
        String otp = webSMSRedis.get(user.getPhone());

        if (EmptyUtils.isEmpty(otp)){
            result.setCode(1);
            result.setMsg("验证码已过期,请重新获取!");
            return result;
        }
        if (!otp.equals(user.getsMSCode())){
            result.setCode(1);
            result.setMsg("验证码错误,请重新输入!");
            return result;
        }
        if (webUsersService.insertUser(user)>0){
            result.setCode(0);
            result.setMsg("注册成功");
            return result;
        }
        result.setCode(1);
        result.setMsg("注册失败,请稍后再试试");
        return result;
    }

 

Guess you like

Origin blog.csdn.net/weixin_38676276/article/details/108503712