JavaWeb之Ajax的基本使用與實戰(zhàn)案例
一、Ajax是什么?
Ajax,全稱Asynchronous JavaScript and XML ,也就是異步加載的javascript 和 XML
.Ajax是一種用于創(chuàng)建快速動態(tài)網(wǎng)頁的技術。
通過在后臺與服務器進行少量數(shù)據(jù)交換,Ajax可以使網(wǎng)頁實現(xiàn)異步更新。這意味著可以在不重新加載整個網(wǎng)頁的情況下,對網(wǎng)頁的某部分進行更新。
JavaScript:更新局部的網(wǎng)頁
XML:一般用于請求數(shù)據(jù)和響應數(shù)據(jù)的封裝
XMLHttpRequest對象:發(fā)送請求到服務器并獲得返回結果
CSS:美化頁面樣式
異步:發(fā)送請求后不等返回結果,由回調(diào)函數(shù)處理結果
二、為什么使用Ajax?
??無刷新:不刷新整個頁面,只刷新局部
??無刷新的好處:只更新部分頁面,有效利用帶寬,提高用戶體驗
三、Ajax基本使用
??通過 HTTP 請求加載遠程數(shù)據(jù)。
1、$.ajax()
常用參數(shù) | 說明 |
url | 一個用來包含發(fā)送請求的URL字符串(請求地址) |
type | 請求方式 (“POST” 或 “GET“[默認]) |
data | 發(fā)送到服務器的數(shù)據(jù)(參數(shù)) |
dataType | 預期服務器返回的數(shù)據(jù)類型(xml、json、text) |
dataType | 請求成功的回調(diào)函數(shù) |
error | 請求失敗的回調(diào)函數(shù) |
??通過遠程 HTTP POST /GET請求載入信息。
這是一個簡單的 POST /GET請求功能以取代復雜 $.ajax 。請求成功時可調(diào)用回調(diào)函數(shù)。如果需要在出錯時執(zhí)行函數(shù),請使用 $.ajax。
2、$.post()
常用參數(shù) | 說 明 |
url | 一個用來包含發(fā)送請求的URL字符串(請求地址) |
data | 發(fā)送到服務器的數(shù)據(jù)(參數(shù)) key/value |
success(data) | 請求成功的回調(diào)函數(shù) |
type | 返回內(nèi)容格式(xml、json、text等) |
3.$.get()
常用參數(shù) | 說 明 |
url | 一個用來包含發(fā)送請求的URL字符串(請求地址) |
data | 發(fā)送到服務器的數(shù)據(jù)(參數(shù)) key/value |
success(data) | 請求成功的回調(diào)函數(shù) |
type | 返回內(nèi)容格式(xml、json、text等) |
三種方法代碼如下:
$.get("url",data,fun(){},"text") $.post("url",data,fun(){},"text") $.ajax({ url:"", type:"get|post", data:{}, dataType:"", success(){} })
四、案例
無刷新登錄(ajax、get、post)
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <title>Title</title> <script src="js/jquery-3.3.1.js"></script> <link rel="icon" href="Icon/bb.png" rel="external nofollow" type="text/x-icon"> </head> <body> <div> <p><input id="account" name="account"></p> <p><input id="password" name="password"></p> <button onclick="login()">登錄</button> </div> <script> function login() { //取到頁面的值 let account = $("#account").val() let password = $("#password").val() //通過jquery來發(fā)送請求ajax去后臺 login.do //ajax方法:get|post $.ajax({ url:"login.do",//訪問地址 data:{account,password},//攜帶的數(shù)據(jù) dataType:"text",//希望后臺給你什么樣子的數(shù)據(jù) type: "get",//什么請求類型 success(resp){ if (resp.trim() === "yes") { alert("登陸成功") location.href = "index.jsp" } else { alert("登陸失敗") } },//成功 error(){ }//錯誤 }) //get請求 /** $.get( //請求地址 "login.do", //攜帶過去的數(shù)據(jù) 直接放數(shù)據(jù),名字就是數(shù)據(jù)的名字 {account, password}, //回調(diào)函數(shù) 請求之后會調(diào)用這個函數(shù) //resp就是后臺給我的值 function (resp) { //trim 去空格 //contains 包含 if (resp.trim() === "yes") { alert("登陸成功") location.href = "index.jsp" } else { alert("登陸失敗") } }, "text" //希望后臺給我的是普通的文本 ) **/ /** $.get("url",data,fun(){},"text") $.post("url",data,fun(){},"text") $.ajax({ url:"", type:"get|post", data:{}, dataType:"", success(){} }) **/ } </script> </body> </html>
LoginServlet.java
ackage com.zking.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/login.do") public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //獲取表單數(shù)據(jù) String account = req.getParameter("account"); String password = req.getParameter("password"); //調(diào)用biz去數(shù)據(jù)庫做驗證 PrintWriter out = resp.getWriter(); if("root".equals(account)&&"root123".equals(password)){ out.println("yes"); }else{ out.println("no"); } } }
查詢名字是否存在
效果圖如下:
如果輸入的內(nèi)容在集合中有的話則提示用戶名已經(jīng)存在 并且按鈕禁用
若沒有則顯示??標簽
register.java
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <title>Title</title> <script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script> <style> #tip{ color: red; } </style> </head> <body> <p><input id="name" onkeyup="yz()" type="text" placeholder="請輸入你的用戶名"><span id="tip"></span></p> <button id="register">去注冊</button> <script> function yz(){ //獲取數(shù)據(jù) let name=$("#name").val(); console.log(name) //發(fā)送請求 $.get("find.do",{name},(resp)=>{ if(resp.trim()==="true"){ $("#tip").text("用戶名已經(jīng)存在") $("#register").prop("disabled",true) }else{ $("#tip").text("????") $("#register").prop("disabled",false) } },"text") } </script> </body> </html>
FindServlet.java
package com.zking.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; /** * 驗證用戶名是否存在 **/ @SuppressWarnings("all") @WebServlet("/find.do") public class FindServlet extends HttpServlet { //數(shù)據(jù)庫中存在的名字 List<String> list = new ArrayList<String>(); { list.add("小明"); list.add("小黃"); list.add("小黑"); list.add("小紫"); list.add("小綠"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //去數(shù)據(jù)庫查詢 String name = req.getParameter("name"); boolean f=false; for (String n : list) { if(n.equals(name)){ f=true; break; } } //需要把結果告訴前臺 PrintWriter out = resp.getWriter(); out.println(f); } }
使用搜索框時彈出的提示
效果圖如下:
index.java
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title>Title</title> <script src="js/jquery-3.3.1.js"></script> </head> <body> ??<input id="keyWord" name="keyWord" onkeyup="search()"> <ul id="list"> </ul> <script> function search(){ //得到輸入框的值 let keyWord=$("#keyWord").val() //發(fā)送到負責檢索商品名稱的servlet $.get("search.do",{keyWord},(resp)=>{ //清空原來的選項 $("#list").empty() //resp現(xiàn)在是從字符串變成了數(shù)組 for(let n of resp){//foreach $("#list").append("<li>"+n+"</li>") } },"json"); } //json //對象的字符串格式,json有固定的格式 //將對象變成json //將json還原為對象 </script> </body> </html>
SearchServlet.java
package com.zking.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; /** * 查詢出對應關鍵字的商品名稱 **/ @WebServlet("/search.do") public class SearchServlet extends HttpServlet { //數(shù)據(jù)庫中存在的商品名字 List<String> list = new ArrayList<String>(); { list.add("楊枝甘露"); list.add("珍珠奶茶"); list.add("焦糖奶茶"); list.add("雀巢咖啡"); list.add("蜜桃四季春"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //去數(shù)據(jù)庫查詢 String keyWord = req.getParameter("keyWord"); //新建一個集合 List<String> ns=new ArrayList<String>(); for (String n : list) { if(n.contains(keyWord)){ ns.add(n); } } //設置響應的編號 resp.setCharacterEncoding("utf-8"); //需要把結果告訴前臺 PrintWriter out = resp.getWriter(); //需要將集合變成json //1.需要獲取轉換對象 ObjectMapper mapper=new ObjectMapper(); //2.調(diào)用方法 String str = mapper.writeValueAsString(ns); out.println(str); } }
注意: 遍歷出來的集合要變成jsno字符串
總結
到此這篇關于JavaWeb之Ajax的基本使用與案例的文章就介紹到這了,更多相關JavaWeb Ajax基本使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
java 操作gis geometry類型數(shù)據(jù)方式
這篇文章主要介紹了java 操作gis geometry類型數(shù)據(jù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03