实现一个ajax请求的简单例子

效果:在前端页面的text框输入一个id,点击按钮,发送ajax请求到数据库查询对应用户数据返回,将用户信息显示在页面,实现局部刷新。

不说废话直接来!

1.前端的jsp页面 (代码的注释写的非常详细了,直接看代码就行了,我就不再解释了)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <title>测试ajax</title>

    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
        $(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("测试异步")
        }
    </script>

</head>
<body>

<input type="text" id="userId"/>
<button onclick="method();">获取</button>
<div>名字:<span id="name"></span></div>
<div>年龄<span id="age"></span></div>
</body>
</html>

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依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

3.UserService

package 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.UserMapper

package 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.User

package 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');

7.测试:成功!

  • 14
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值