效果:在前端页面的text框输入一个id,点击按钮,发送ajax请求到数据库查询对应用户数据返回,将用户信息显示在页面,实现局部刷新。
1.前端的jsp页面 (代码的注释写的非常详细了,直接看代码就行了,我就不再解释了)
测试ajax$(document).ready(function () {
});
function method() {
var val = $("#userId").val();
$.ajax({
type:"GET",
url:"getUser",
// data:{"id":val}, // data参数是可选的,有多种写法,也可以直接在url参数拼接参数上去,例如这样:url:"getUser?id="+val,
data:"id="+val,
async:true, // 异步,默认开启,也就是$.ajax后面的代码是不是跟$.ajx里面的代码一起执行
cache:true, // 表示浏览器是否缓存被请求页面,默认是 true
dataType:"json", // 返回浏览器的数据类型,指定是json格式,前端这里才可以解析json数据
success:function(data){
$("#name").text(data.name);
$("#age").text(data.age);
},
error:function(){
console.log("发生错误")
alert("发生错误");
},
complete:function(){
console.log("ajax请求完事,最终操作在这里完成")
}
});
// alert("测试异步")
}
获取
2.controller的代码// 访问jsp页面
@RequestMapping("/testAjax")
public String testAjax(){
return "TestAjax";
}
// jsp页面的请求url
@RequestMapping("/getUser")
@ResponseBody
public String getUser(String id) throws InterruptedException {
User user = userService.get(id);
User user1 = new User();
String s = JSON.toJSONString(user1); // 就算数据库查不到也不会返回Null
if(user!=null){
s = JSON.toJSONString(user);
}
// Thread.sleep(5000); // 测试异步就放开它
return s;
}
这里 getUser 方法里面用到了阿里的 fastjson的json解析工具(用来对象转json字符串的),放个maven依赖
com.alibaba
fastjson
1.2.47
3.UserServicepackage com.liqiye.springbootdemo.service;
import com.liqiye.springbootdemo.entity.User;
import com.liqiye.springbootdemo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* @author liqiye
* @description
* @date 2019/4/6
*/
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User get(String id){
return userMapper.get(id);
}
}
4.UserMapperpackage com.liqiye.springbootdemo.mapper;
import com.liqiye.springbootdemo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
// @Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
User get(@Param("id")String id);
}
5.Userpackage com.liqiye.springbootdemo.entity;
import com.liqiye.springbootdemo.utils.SetName;
/**
* @author liqiye
* @description
* @date 2019/4/6
*/
public class User {
public Integer id;
@SetName(value = "张三")
public String name;
public Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public User() {
}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
6.数据库DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', '张三', '23');
INSERT INTO `user` VALUES ('2', '李四', '24');
INSERT INTO `user` VALUES ('3', '王五', '25');