ajax前后台交互简单实例

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;
    }

maven依赖 pom.xml中

<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.测试成功

 

posted @ 2020-09-29 16:39  LW_20171224  阅读(80)  评论(0)    收藏  举报