版权声明: https://blog.csdn.net/weixin_40550726/article/details/82951617
通过jQuery ajax实现从服务器查询数据,返回给前端并显示到html页面
html文件
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>使用 jQuery validate 表单验证</title>
<script th:src="@{/scripts/jquery-3.3.1.min.js}"></script>
<script th:src="@{/scripts/jquery.validate.min.js}"></script>
<script th:src="@{/scripts/messages_zh.min.js}"></script>
<script th:src="@{/scripts/user/login.js}"></script>
</head>
<body>
<form id="form1" action="/userLogin">
<input type="text" id="userName" class="userName" name="userName"><br>
<input type="email" id="email" name="email"><br>
<select id="depertmentId" name="departmentId">
</select><br>
<input type="password" id="password" class="password" name="password"><br>
<input type="submit" value="login">
</form>
</body>
</html>
login.js文件
function findAllDepts() {
$.ajax({
async : false, //表示请求是否异步处理
type : "post", //请求类型
url : "/getDepts",//请求的 URL地址
dataType : "json",//返回的数据类型
success: function (data) {
console.log(data); //在控制台打印服务器端返回的数据
for(var i=0;i<data.length;i++){
console.log(data[i].deptId+" "+data[i].deptName);
}
$("select[name='depertmentId']").empty();
$("select[name='depertmentId']").append('<option value="">——请选择——</option>');
for(var i=0;i<data.length;i++){
var html ='<option value="'+data[i].deptId+'">';
html +=data[i].deptName + '</option>';
$("select[name='departmentId']").append(html); //将数据显示在html页面
}
},
error:function (data) {
alert(data.result);
}
});
};
$(document).ready(function () {
findAllDepts(); //页面加载完成就执行该方法
});
后端对应的请求方法(项目为springboot项目)
package com.njxz.demo.controller;
import com.njxz.demo.domain.Department;
import com.njxz.demo.domain.User;
import com.njxz.demo.service.IUserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@RestController
public class UserController {
@Resource
private IUserService userService;
@RequestMapping("/getDepts")
public List<Department> getDepts(){ //查找所有部门
List<Department> depts=userService.findAllDepts();
return depts;
}
}
后端返回的对象类
package com.njxz.demo.domain;
public class Department {
private Integer deptId;
private String deptName;
public Integer getDeptId() {
return deptId;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName == null ? null : deptName.trim();
}
}
控制台打印的数据信息
html页面显示效果