Ajax实现异步加载数据
本文实例为大家分享了ajax实现异步加载数据的具体代码,供大家参考,具体内容如下
项目结构如下 (需要导入一个jquery的包,配置文件web.xml和springmvc-servlet.xml,不在写了,不知道的可以看一下我其它的博客,上边都有)
异步加载数据
首先创建一个实体类
package com.zkw.pojo; import lombok.allargsconstructor; import lombok.data; import lombok.noargsconstructor; @data @allargsconstructor @noargsconstructor public class user { private string name; private int age; private string sex; }
然后创建一个controller
package com.zkw.controller; import com.zkw.pojo.user; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.restcontroller; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.ioexception; import java.util.arraylist; import java.util.list; @restcontroller public class ajaxcontroller { @requestmapping("/a2") public list test2(){ list userlist = new arraylist(); userlist.add(new user("七七",1,"女")); userlist.add(new user("琪琪",1,"女")); userlist.add(new user("琦琦",1,"女")); return userlist; } }
最后创建一个jsp页面
<%@ page contenttype="text/html;charset=utf-8" language="java" %>ajax异步数据加载 $(function () { $("#btn").click(function () { $.post("${pagecontext.reques-t.contextpath}/a2",function (data) { var html=""; for (let i = 0; i < data.length; i++){ html +="" + " " } $("#content").html(html); }) }) })" + data[i].name +" "+ "" + data[i].age +" "+ "" + data[i].sex +" "+ "
姓名 | 年龄 | 性别 |
结果如下
用户登录的异步验证
先创建一个controller
package com.zkw.controller; import com.zkw.pojo.user; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.restcontroller; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.ioexception; import java.util.arraylist; import java.util.list; @restcontroller public class ajaxcontroller { @requestmapping("/a3") public string test3(string username,string pwd){ string msg =""; if (username != null){ if (username.equals("admin")){ msg = "ok"; }else{ msg = "用户名不存在"; } } if (pwd != null){ if (pwd.equals("123456")){ msg = "ok"; }else{ msg = "密码输入错误"; } } return msg; } }
然后创建一个jsp页面
<%@ page contenttype="text/html;charset=utf-8" language="java" %>用户登录 function a1() { $.post({ url:"${pagecontext.request.contextpath}/a3", data:{"username":$("#username").val()}, success(data){ if (data.tostring()==="ok"){ $("#userinfo").css("color","green"); }else { $("#userinfo").css("color","red"); } $("#userinfo").html(data); } }) } function a2() { $.post({ url:"${pagecontext.request.contextpath}/a3", data:{"pwd":$("#pwd").val()}, success(data){ if (data.tostring()==="ok"){ $("#pwdinfo").css("color","green"); }else { $("#pwdinfo").css("color","red"); } $("#pwdinfo").html(data); } }) }用户名:
密码名:
结果如下