thymeleaf模版引擎

写项目用到了thymeleaf模版引擎,然后前后端交互用model存数据,然后controller跳转,通过model将数据带过去,利用thymeleaf遍历,这种的话,如果出现错误的情况,前台不好显示提醒。

然后就想着要统一返回格式,这样前端可以根据状态码判断,从而做出提示。(完整代码在下面)

然后就想着用ajax请求,这样可以通过返回数据判断。

本来是想将ajax返回数据传入thymeleaf中遍历的那块,th:each这里,但是这样好像不行。所以只能是传统的方式。遍历拼接html,然后写入。

function todo() {$.ajax({type: "post",contentType: "application/json",url: "/testCoursePage",data: "",//不需要传入数据就没传// beforeSend: function () {//     loadingIndex = layer.msg('处理中', {icon: 16});//},success: function (result) {//layer.close(loadingIndex);console.log(result);if (result.status) {//window.location.href = "main";//alert(result.data);userList=result.data;var inf="<tr>\n" +"                            <th style=\"display: none\">id</th>\n" +"                            <th style=\"display: none\">课程id</th>\n" +"                            <th>课程名称</th>\n" +"                            <th>代课老师</th>\n" +"                            <th>上课时间</th>\n" +"                            <th>剩余人数</th>\n" +"                            <th>操作</th>\n" +"                        </tr>";for (var i=0;i<userList.length;i++){var course=userList[i];inf+= "<tr> <td style=\"display: none\" >"+course.id+"</td> <td style=\"display: none\">"+course.courseid+"</td>"+"<td>"+course.coursename+"</td> <td >"+course.teachername+"</td> <td>"+course.description+"</td> <td >"+course.number+"</td>"+"<td><a type=\"button\" class=\"layui-btn layui-btn-sm\" >确认选课</a></td></tr>";}$("#table2").html(inf);//写入table中} else {alert("获取错误!")}}});}

参数:

注意Content-Type:
1. 使用Ajax默认格式来传递数据【推荐】
Ajax的默认格式为:application/x-www-form-urlencoded,相当于(username=“admin”&password=123)来传递数据(这是GET请求的固定格式)

前端代码:
当Ajax以默认格式上传时,data数据直接使用JSON对象user,不用转换为JSON字符串(很方便)

此时写data : user,

var user= {"username" : username,"password" : password,"rememberMe":rememberMe};$.ajax({url : "http://...../jsontest.do",type : "POST",async : true,data : user,dataType : 'json',success : function(data) {}});

后端使用@RequestParam注解或省略注解都可以接收到传来的数据:
【推荐】

//直接省略注解
@RequestMapping("/jsontest.do")public void test(User user,String username,String password,Boolean rememberMe){System.out.println(user);System.out.println("username: " + username);System.out.println("password: " + password);System.out.println("rememberMe: " + rememberMe);}

优点:
1).前端传递数据不用转换为json字符串:JSON.stringify(user)
2).后端接受的参数很灵活,即可以封装为User对象,亦可以使用单个参数username,rememberMe,甚至User对象和单个rememberMe参数混合使用都可以

2. 使用application/json格式来传递数据
Content-Type使用application/json的时候,要将JSON对象转换为JSON字符串
前端代码:
这里 data : JSON.stringify(user),

var user= {"username" : username,"password" : password};$.ajax({url : "http://...../jsontest.do",type : "POST",async : true,contentType: "application/json; charset=utf-8",data : JSON.stringify(user),dataType : 'json',success : function(data) {}});

后端必须使用 @RequestBody 注解:

//这种方式下所有的参数都只能封装在User对象中,不能单独设置参数@RequestMapping("/jsontest")public void test(@RequestBody User user ){String username = user.getUsername();String password = user.getPassword();}//或者
@RequestMapping("/jsontest")public void test(@RequestBody Map map ){String username = map.get("username").toString();String password = map.get("password").toString();}//或者
public void test(@RequestBody String jsonData) {JSONObject jsonObject = JSON.parseObject(jsonData);String username= jsonObject.getString("username");String username= jsonObject.getString("password");}

缺点:
1.前端需要使用JSON.stringify()将JSON对象转换为JSON字符串
2.后端在接受参数的时候比较麻烦,没有第1种简单,也没有第一种灵活


统一返回格式完整代码:

package com.jf.common;import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;import java.io.Serializable;@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
//保证序列化值为null时候,key不序列化
public class ServerResponse<T> implements Serializable {private int status;private String msg;private T data;private ServerResponse(int status) {this.status = status;}private ServerResponse(int status, T data) {this.status = status;this.data = data;}private ServerResponse(int status, String msg) {this.status = status;this.msg = msg;}private ServerResponse(int status, String msg, T data) {this.status = status;this.msg = msg;this.data = data;}@JsonIgnore//忽略public boolean isSuccess(){return this.status==ResponseCode.SUCCESS.getStatus();}public int getStatus() {return status;}public String getMsg() {return msg;}public T getData() {return data;}public static  <T>ServerResponse<T> createBySuccess(){return new ServerResponse<T>(ResponseCode.SUCCESS.getStatus());}public static  <T>ServerResponse<T> createBySuccessMessage(String msg){return new ServerResponse<T>(ResponseCode.SUCCESS.getStatus(),msg);}public static  <T>ServerResponse<T> createBySuccess(T data){return new ServerResponse<T>(ResponseCode.SUCCESS.getStatus(),data);}public static  <T>ServerResponse<T> createBySuccess(String msg,T data){return new ServerResponse<T>(ResponseCode.SUCCESS.getStatus(),msg,data);}public static  <T>ServerResponse<T> createByError(){return new ServerResponse<T>(ResponseCode.ERROR.getStatus(),ResponseCode.ERROR.getMsg());}public static  <T>ServerResponse<T> createByErrorMessage(String errorMsg){return new ServerResponse<T>(ResponseCode.ERROR.getStatus(),errorMsg);}public static  <T>ServerResponse<T> createByErrorMessage(int errorStatus,String errorMsg){return new ServerResponse<T>(errorStatus,errorMsg);}}
package com.jf.common;public enum ResponseCode {SUCCESS(1,"SUCCESS"),ERROR(0,"ERROR"),NEED_LOGIN(10,"NEED_LOGIN"),ILLEGAL_ARGUMENT(2,"ILLEGAL_ARGUMENT");private final int status;private final String msg;ResponseCode(int status, String msg) {this.status = status;this.msg = msg;}public int getStatus() {return status;}public String getMsg() {return msg;}
}

jsp注意jquery路径,防止项目发布后找不到jquery。

thymeleaf中用ajax相关推荐

  1. SpringBoot不使用Thymeleaf的ajax成功后html跳转

    一.SpringBoot不使用Thymeleaf的ajax成功后html跳转 如图所示,ajax请求成功之后,这样子跳转页面是失败的 二.解决办法 在该目录下新建static文件夹,把html放在这里

  2. jQuery中用ajax访问php接口文件

    js代码 function ajax_request(){var result;var articleId = new Object();articleId=getArticleId();$.ajax ...

  3. SpringBoot中使用thymeleaf时ajax请求不能回显消息

    场景 在SpringBoot项目中使用thymeleaf模板时,在js文件中使用ajax提交表单 不能成功回显消息. 实现 修改为 html中: <button id="parseBt ...

  4. 解决在thinkphp5.0中用ajax访问后台控制器方法时,返回的数据显示不出来

    错误代码如下: $.post("{:url('changeStatus')}",{"id":$(this).attr("id")},func ...

  5. bootstrap validator ajax提交,bootstrapValidator中用ajax校验

    xlh : { validators : { trigger : 'change', notEmpty : { message : '序列号不能为空' }, threshold : 15,// 有2字 ...

  6. ie中用ajax提示未定义,Jquery在IE7下无法使用 $.ajax解决方法

    通过查看源码发现 // Create the request object; Microsoft failed to properly // implement the XMLHttpRequest ...

  7. android表单错误提示,安卓微信中用$.ajax提交表单一直返回error

    在其他手机浏览器和iphone的微信中都没问题,只有在安卓的微信中会返回error,XMLHttpRequest.status 为 200, XMLHttpRequest.readyState 为 4 ...

  8. PHP+mysql+ajax搭建图书管理系统

    经过这次开发还是有了很深的感悟,虽然这是一个很小的前后端结合的项目,但毕竟是自己亲手将它"生下"嘛,还是很珍惜它,而且也的确让我稍有成长. 历时:两个星期 技术:mysql+php ...

  9. Thinkphp ajax分页

    Thinkphp中用ajax分页和普通的ajax分页的区别在于处理位置的不同,thinkphp是在控制器的方法中处理ajax传的值,然后返回数据.下面是一个点击事件触发后,显示的内容用ajax分页. ...

最新文章

  1. python 错误之SyntaxError: Missing parentheses in call to 'print'
  2. #串口通信超时处理_简单通信协议
  3. 《从零构建前后分离web项目》:开篇 - 纵观WEB历史演变
  4. mysql repair 索引_mysql 删除行会重建索引吗
  5. java 单机版_JAVA单机版管理系统源代码.pdf
  6. Androidstudio无法修改按钮颜色
  7. OCA读书笔记(1) - 浏览Oracle数据库架构
  8. mac系统在云服务器地址,mac如何登陆云服务器地址
  9. 两个重要极限_算法数学基础-概率论最重要两个结论:大数定律及中心极限定理...
  10. 我也属于80这个年代
  11. Mysql 扩展性设计之Replication,在Mysql具有很相当重要的位置,主从、主主从,你了解他们的背后逻辑吗
  12. 网络层(网际控制报文协议ICMP)
  13. android天气预报----google开源天气API,SAX解析
  14. 【软件测试】测试用例详解
  15. android 自定义字体 ttf,Android使用自定义字体的方法
  16. 《人类简史-从动物到上帝》读后感
  17. 新手怎样才能快速的学会建网站
  18. 渗透测试-Kali虚拟机技术
  19. mac之间迁移微信聊天记录
  20. 一个简单的C语言程序(详解)

热门文章

  1. html5 jstree树形菜单,树形插件jsTree
  2. 如何查看Linux版本信息?
  3. mktime() 函数
  4. nikita popov php,PHP新知:PHP 7.4 新语法:箭头函数
  5. C语言:两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。排出比赛名单
  6. 两个乒乓球队进行比赛问题 C++实现
  7. 从零开始搭建ROS小车(上位机部分)(一)
  8. vscode指定扩展安装位置
  9. Visual Studio打开VC6.0 dsw工程,转换为sln
  10. 【PMP】PMBOK 笔记 第9章 项目人力资源管理