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); } }) }用戶名:
密碼名:
結果如下