【SpringBoot】Thymeleaf融合ajax

文章目录

效果

局部刷新
不会出现表单重复提交

在这里插入图片描述

ajax.html

<!DOCTYPE html>
<!--<html lang="en" xmlns:th="http://www.springframework.org/schema/jdbc">-->
<!--<html lang="en">-->
<html xmlns: th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
<div>
    <span>该区域不会被刷新</span>
<!--    <Button id="button">刷新</Button>-->
    <div id="child_view">
        <span>该区域会被刷新</span>
    </div>
</div>

<!--不带文件的表单-->
<!-- <form id="addForm" action="/json" method="post">
    <input type="text" name="name" placeholder="请输入名字" />
    <input type="password" name="password" placeholder="密码"/>
</form>
<button type="button" id="submitAdd">确认</button>
 -->
<!--带文件的表单-->
<form id="addForm" action="/json" method="post"enctype=" multipart/form-data">
    <input type="text" name="name" placeholder="请输入名字" />
    <input type="password" name="password" placeholder="密码"/>
    <input type="file" name="file" />
</form>
<button type="button" id="submitAdd">确认</button>

<!--<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>-->
<script src="/js/jquery-3.3.1.min.js"></script>
<!-- 
 注意:thymeleaf要改的静态资源路径引入js
 spring:
   thymeleaf:
     cache: false
   resources:
     static-locations: classpath:/templates,classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
 -->

<script type = "text/javascript" th:inline="javascript">
    /*<![CDATA[*/
    var basePath = /*[[${
    
    #httpServletRequest.getScheme() + "://" + #httpServletRequest.getServerName() + ":" + #httpServletRequest.getServerPort() + #httpServletRequest.getContextPath()}]]*/;


    $('#button').bind('click', function () {
    
    
            refresh();
        });

    function refresh() {
    
    
        $.ajax({
    
     //refresh
            url: basePath + '/json',
            type: 'post',
            dataType: 'text',
            data: {
    
    

            },
            cache: false,
            async: true,
            success: function (data) {
    
    
                var json = eval("(" + data + ")")
                console.log(data)
                console.log(json)
                 $("#child_view").empty();
                 $("#child_view").append(data);
            }
        });
    }

/*    $("#submitAdd").click(function(){
    
    
      var targetUrl = $("#addForm").attr("action");
      var data = $("#addForm").serialize();
	  console.log(basePath)
	  console.log(targetUrl)
	  console.log(data)
       $.ajax({
    
    
        type:'post',
        url:basePath + targetUrl,
        cache: false,
		async: true,
        data:data,  //重点必须为一个变量如:data
<!--        dataType:'json',-->
        success:function(data){
    
    
			console.log("sucess")
			console.log(data)
			alert(data.name)
        },
        error:function(){
    
    
         alert("请求失败")
        }
       })

    }) */
	

   // 带文件的表单
   $("#submitAdd").click(function(){
    
    
       var targetUrl = $("#addForm").attr("action");
       var data = new FormData($( "#addForm" )[0]);
	   console.log(basePath)
	   console.log(targetUrl)
	   console.log(data)
	   
        $.ajax({
    
    
         type:'post',
         url:basePath+targetUrl,
         cache: false,    //上传文件不需缓存
		 async: true,
         processData: false, //需设置为false。因为data值是FormData对象,不需要对数据做处理
         contentType: false, //需设置为false。因为是FormData对象,且已经声明了属性enctype="multipart/form-data"
         data:data,
         // dataType:'json',
         success:function(data){
    
    
           console.log("sucess")
           console.log(data)
           console.log(data.name)
		   $("#child_view").empty();
		   $("#child_view").append(data.file);
         },
         error:function(){
    
    
          alert("请求失败")
         }
        })
     })

    /*]]>*/
</script>
</body>
</html>

Controller

package com.ths.arsenaldnsnginxconfig.controller;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

//@Controller
@RestController
public class AjaxController {
    
    

    @RequestMapping("/ajax")
    public ModelAndView ajax() {
    
    
        return new ModelAndView("ajax");
    }

    @RequestMapping("/refresh")
    public String refresh(){
    
    
        return "refresh";
    }
    

    @RequestMapping("/json")
    public JSON json(String name, String password, MultipartFile file) {
    
    

        JSONObject jsonObject = new JSONObject();
        jsonObject.putOpt("name", name);
        jsonObject.putOpt("pwd", password);
        System.out.println(file);
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getOriginalFilename().length());
        if (file.getOriginalFilename().length() != 0) {
    
    
            jsonObject.putOpt("file", file.getOriginalFilename());
        }else {
    
    
            jsonObject.putOpt("file", "错误:请上传文件,再重新提交");
        }
        return jsonObject;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43469680/article/details/120743201
今日推荐