表单提交由submit改为异步的方式

发布时间 2023-10-07 14:22:57作者: 爱跳舞的程序员

1,submit方式(页面会按action的url跳转,这个不方便一些交互)

function saveSingleYx(){
    $('#myTwoForm').submit();
}

2,ajax异步方式

function saveSingleYx(){
    //document.getElementById('myTwoForm').setAttribute("action", "saveSingleYx.ht");
     //$("myTwoForm").submit(function (event) {
         //event.preventDefault(); // 阻止表单的默认提交行为
         var formData =  $('#myTwoForm').serialize(); // 序列化表单数据                 
         $.ajax({
             url: "saveSingleYx.ht",
             type: "POST",
             data: formData,
             success: function (response) {
                 // 请求成功,处理后端返回的数据
                 console.log(response);
                 alert(response);
                 window.location.reload();
             },
             error: function () {
                 // 请求失败,处理错误情况
                 console.log("保存失败!!");
             }
         });
     //});
}

 

java后端

    @RequestMapping("saveSingleYx")
    @Action(description = "保存")
    @org.springframework.web.bind.annotation.ResponseBody
    public String saveSingleYx(HttpServletRequest request, HttpServletResponse response, Yjsydbsplc yjsydbsplc) throws Exception {
        String resString= "保存成功";try {
            List<Sydbyxsub> initSubAll = this.initSubAll(request);
            if (initSubAll!=null) {
                sydbyxsubService.batchUpdate(initSubAll);
            }else {
                logger.info("initSubAll=" + initSubAll);
            }
        } catch (Exception e) {
            resString  = "保存失败 请联系管理员!!"+e.getMessage();
        }
        return resString;
    }