JSON&Ajax03
4.jQuery的Ajax請求
原生Ajax請求問題分析:
- 撰寫原生的Ajax要寫很多的代碼,還要考慮瀏覽器兼容問題,使用不方便
- 在實際作業中,一般使用JavaScript的框架(比如jquery)發動Ajax請求,從而解決這個問題,
4.1jQuery Ajax操作方法
在線檔案:jQuery 參考手冊 - Ajax (w3school.com.cn)
4.2$.ajax()方法
完整的引數查看手冊:jQuery ajax - ajax() 方法
$.ajax 常用引數:
-
url:請求的地址
-
type:請求的方式get或者post, 默認為 "GET",
注意:其它 HTTP 請求方法,如 PUT 和 DELETE 也可以使用,但區域分瀏覽器支持,
-
data:發送到服務器的資料,將自動轉換為請求字串格式
-
success:請求成功后的回呼函式
引數:由服務器回傳,并根據 dataType 引數進行處理后的資料;描述狀態的字串,
這是一個 Ajax 事件,
-
error:默認值: 自動判斷 (xml 或 html),請求失敗時的回呼函式,
-
dataType:指定回傳的資料型別,常用json或text
4.3$.get()和$.post()請求
jQuery AJAX get() 和 post() 方法
$.get()請求和$.post()請求常用引數:
- url:請求的url地址
- data:請求發送到服務器的資料
- success:成功時的回呼函式
- type:回傳內容的格式,xml,html,script,json,text
說明:
$.get()和$.post()底層還是使用$.ajax()方法來實作異步請求
4.3.1$.get()
get() 方法通過遠程 HTTP GET 請求載入資訊
這是一個簡單的 GET 請求功能以取代復雜 $.ajax,請求成功時可呼叫回呼函式,如果需要在出錯時執行函式,請使用 $.ajax().
語法:
$(selector).get(url,data,success(response,status,xhr),dataType)
4.3.2$.post()
post() 方法通過 HTTP POST 請求從服務器載入資料,
語法:
jQuery.post(url,data,success(data, textStatus, jqXHR),dataType)
4.4$.getJSON()方法
jQuery ajax - getJSON() 方法
$.getJSON()常用引數
- url:請求發送哪個url
- data:請求發送到服務器的資料
- success:請求成功時運行的函式
說明:
$.getJSON()底層使用$.ajax()方法來實作異步請求
$.getJSON()方法通過 HTTP GET 請求載入 JSON 資料,語法:
jQuery.getJSON(url,data,success(data,status,xhr))
4.5應用實體
4.5.1$.ajax()應用實體
演示jquery發送ajax的案例
- 在輸入框輸入用戶名
- 點擊驗證用戶名,服務端驗證該用戶是否已經占用了,如果是,則以json格式回傳該用戶資訊
- 假定king為已使用的用戶名
- 對頁面進行區域重繪,顯示回傳的資訊
思路分析:直接參考3.2的思路圖即可
引入jquery庫:
注意:如果有的資源是拷貝進來的,有時候運行目錄out沒有及時更新,這時可以點擊Rebuild Project,如果不行就redeploy Tomcat
配置servlet:
<servlet>
<servlet-name>CheckUserServlet2</servlet-name>
<servlet-class>com.li.ajax.servlet.CheckUserServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckUserServlet2</servlet-name>
<url-pattern>/checkUserServlet2</url-pattern>
</servlet-mapping>
創建CheckUserServlet2:
package com.li.ajax.servlet;
import com.google.gson.Gson;
import com.li.ajax.entity.User;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class CheckUserServlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接收jquery發送的ajax資料
String username = request.getParameter("username");//引數名取決于前端的引數名
response.setContentType("text/json;charset=utf-8");//指定MIME型別為json
Gson gson = new Gson();
if ("king".equals(username)) {
//后面可以接入資料庫database
User user = new User(100, "king", "123", "[email protected]");
response.getWriter().print(gson.toJson(user));
} else {
//回傳一個不存在的User-->測驗
User user = new User(-1, "", "", "");
response.getWriter().print(gson.toJson(user));
}
}
}
login2.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用戶注冊</title>
<!-- 引入jquery-->
<script type="text/javascript" src="https://www.cnblogs.com/liyuelian/archive/2022/12/09/script/jquery-3.6.1.min.js"></script>
<script type="text/javascript">
$(function () {
//系結事件
$("#btn1").click(function () {
//發出ajax請求
/**
* 1.指定引數時,需要在{}里面
* 2.指定引數時,需要指定引數名
* 3.dataType:"json" 代表要求服務器回傳的資料是json,
* 如果服務器回傳的不是json,就會決議出錯
*/
$.ajax({
url: "/ajax/checkUserServlet2",
type: "post",
data: {//這里我們直接給一個json
username: $("#uname").val(),
date : new Date()//防止瀏覽器快取
},
error:function () {//失敗后的回呼函式
console.log("失敗")
},
success:function (data,status,xhr) {
console.log("成功");
console.log("data="https://www.cnblogs.com/liyuelian/archive/2022/12/09/,data);
console.log("status=",status);
console.log("xhr=",xhr);
//data是一個json物件,需要轉成json字串
$("#div1").html(JSON.stringify(data));
//對回傳的結果進行處理
if (""==data.username){//說明用戶名可用
$("#myres").val("該用戶名可用");
}else {
$("#myres").val("該用戶名不可用");
}
},
dataType:"json"
})
})
})
</script>
</head>
<body>
<h1>用戶注冊-Jquery+Ajax</h1>
<form action="/ajax/checkUserServlet2" method="post">
用戶名字:<input type="text" name="username" id="uname">
<input type="button" id="btn1" value="https://www.cnblogs.com/liyuelian/archive/2022/12/09/驗證用戶名">
<input style="border-width: 0;color: red" type="text" id="myres"><br/><br/>
用戶密碼:<input type="password" name="password"><br/><br/>
電子郵件:<input type="text" name="email"><br/><br/>
<input type="submit" value="https://www.cnblogs.com/liyuelian/archive/2022/12/09/用戶注冊">
</form>
<h1>回傳的 json 資料</h1>
<div id="div1"></div>
</body>
</html>
4.5.2$.get()應用實體
使用4.5的應用實體,將上面的html頁面改寫,其他不變,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用戶注冊</title>
<!-- 引入jquery-->
<script type="text/javascript" src="https://www.cnblogs.com/liyuelian/archive/2022/12/09/script/jquery-3.6.1.min.js"></script>
<script type="text/javascript">
$(function () {
//系結事件
$("#btn1").click(function () {
//演示$.get()使用
// $.get()默認是get請求,不需要指定請求方式
//不需要寫引數名,但是引數的位置要正確對應,
// 順序是:url,data,success回呼函式,回傳的資料格式
$.get(
"/ajax/checkUserServlet2",
{//這里我們直接給一個json
username: $("#uname").val(),
date: new Date()//防止瀏覽器快取
},
function (data, status, xhr) {
console.log("$.get成功")
console.log("data="https://www.cnblogs.com/liyuelian/archive/2022/12/09/, data);
console.log("status=", status);
console.log("xhr=", xhr);
//data是一個json物件,需要轉成json字串
$("#div1").html(JSON.stringify(data));
//對回傳的結果進行處理
if ("" == data.username) {//說明用戶名可用
$("#myres").val("該用戶名可用");
} else {
$("#myres").val("該用戶名不可用");
}
},
"json"
)
})
})
</script>
</head>
<body>
<h1>用戶注冊-Jquery+Ajax</h1>
<form action="/ajax/checkUserServlet2" method="post">
用戶名字:<input type="text" name="username" id="uname">
<input type="button" id="btn1" value="https://www.cnblogs.com/liyuelian/archive/2022/12/09/驗證用戶名">
<input style="border-width: 0;color: red" type="text" id="myres"><br/><br/>
用戶密碼:<input type="password" name="password"><br/><br/>
電子郵件:<input type="text" name="email"><br/><br/>
<input type="submit" value="https://www.cnblogs.com/liyuelian/archive/2022/12/09/用戶注冊">
</form>
<h1>回傳的 json 資料</h1>
<div id="div1"></div>
</body>
</html>
4.5.3$.post()應用實體
使用4.5的應用實體,將上面的html頁面改寫,其他不變,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用戶注冊</title>
<!-- 引入jquery-->
<script type="text/javascript" src="https://www.cnblogs.com/liyuelian/archive/2022/12/09/script/jquery-3.6.1.min.js"></script>
<script type="text/javascript">
$(function () {
//系結事件
$("#btn1").click(function () {
//$.post 和 $.get的呼叫方式基本一樣,只是這時是以post方式發送ajax請求
$.post(
"/ajax/checkUserServlet2",
{//這里我們直接給一個json
username: $("#uname").val(),
date: new Date()//防止瀏覽器快取
},
function (data, status, xhr) {
console.log("$.post成功")
console.log("data="https://www.cnblogs.com/liyuelian/archive/2022/12/09/, data);
console.log("status=", status);
console.log("xhr=", xhr);
//data是一個json物件,需要轉成json字串
$("#div1").html(JSON.stringify(data));
//對回傳的結果進行處理
if ("" == data.username) {//說明用戶名可用
$("#myres").val("該用戶名可用");
} else {
$("#myres").val("該用戶名不可用");
}
},
"json"
)
})
})
</script>
</head>
<body>
<h1>用戶注冊-Jquery+Ajax</h1>
<form action="/ajax/checkUserServlet2" method="post">
用戶名字:<input type="text" name="username" id="uname">
<input type="button" id="btn1" value="https://www.cnblogs.com/liyuelian/archive/2022/12/09/驗證用戶名">
<input style="border-width: 0;color: red" type="text" id="myres"><br/><br/>
用戶密碼:<input type="password" name="password"><br/><br/>
電子郵件:<input type="text" name="email"><br/><br/>
<input type="submit" value="https://www.cnblogs.com/liyuelian/archive/2022/12/09/用戶注冊">
</form>
<h1>回傳的 json 資料</h1>
<div id="div1"></div>
</body>
</html>
4.5.4$.getJSON()應用實體
使用4.5的應用實體,將上面的html頁面改寫,其他不變,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用戶注冊</title>
<!-- 引入jquery-->
<script type="text/javascript" src="https://www.cnblogs.com/liyuelian/archive/2022/12/09/script/jquery-3.6.1.min.js"></script>
<script type="text/javascript">
$(function () {
//系結事件
$("#btn1").click(function () {
//如果你通過jquery發出的ajax請求是get請求,并且回傳的資料格式是json,
// 可以直接使用getJSON()函式,很方便
$.getJSON(
"/ajax/checkUserServlet2",
{//這里我們直接給一個json
username: $("#uname").val(),
date: new Date()//防止瀏覽器快取
},
function (data, status, xhr) {//成功后的回呼函式
console.log("$.getJSON成功")
console.log("data="https://www.cnblogs.com/liyuelian/archive/2022/12/09/, data);
console.log("status=", status);
console.log("xhr=", xhr);
//data是一個json物件,需要轉成json字串
$("#div1").html(JSON.stringify(data));
//對回傳的結果進行處理
if ("" == data.username) {//說明用戶名可用
$("#myres").val("該用戶名可用");
} else {
$("#myres").val("該用戶名不可用");
}
}
)
})
})
</script>
</head>
<body>
<h1>用戶注冊-Jquery+Ajax</h1>
<form action="/ajax/checkUserServlet2" method="post">
用戶名字:<input type="text" name="username" id="uname">
<input type="button" id="btn1" value="https://www.cnblogs.com/liyuelian/archive/2022/12/09/驗證用戶名">
<input style="border-width: 0;color: red" type="text" id="myres"><br/><br/>
用戶密碼:<input type="password" name="password"><br/><br/>
電子郵件:<input type="text" name="email"><br/><br/>
<input type="submit" value="https://www.cnblogs.com/liyuelian/archive/2022/12/09/用戶注冊">
</form>
<h1>回傳的 json 資料</h1>
<div id="div1"></div>
</body>
</html>

4.6練習
● 需求分析: 到資料庫去驗證用戶名是否可用
-
點擊驗證用戶名, 到資料庫中驗證用戶名是否可用
-
創建資料庫 ajaxdb , 創建表 user 表 自己設計
-
使用 Jquery + ajax 方式, 服務端驗證該用戶名是否已經占用了, 如果該用戶已經占用,以 json 格式回傳該用戶資訊
-
對頁面進行區域重繪, 顯示回傳資訊
提示: 根據day34-JSON&Ajax02-3.3練習 的 ajax 請求+jdbc+mysql 到資料庫驗證案例完成
根據之前的day34-JSON&Ajax02-3.3練習,我們已經寫了JDBCUtilsByDruid,BaseDAO,UserDAO,UserService,User等類,只需要在CheckUserServlet2中修改一下代碼即可完成:
package com.li.ajax.servlet;
import com.google.gson.Gson;
import com.li.ajax.entity.User;
import com.li.ajax.service.UserService;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;
public class CheckUserServlet2 extends HttpServlet {
private UserService userService = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/json;charset=utf-8");//指定MIME型別為json
Gson gson = new Gson();
//接收jquery發送的ajax資料
String username = request.getParameter("username");//引數名取決于前端的引數名
//到資料庫中查找有無重名用戶
try {
User userByName = userService.getUserByName(username);
//如果有回傳的就是一個User物件,如果沒有,回傳的就是null
response.getWriter().print(gson.toJson(userByName));
} catch (SQLException e) {
e.printStackTrace();
}
}
}
前端html頁面使用4.5.4的$.getJSON()方法發送ajax請求,在4.5.4代碼的基礎上修改回傳資料的判斷條件即可:
測驗結果:
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/539672.html
標籤:其他
上一篇:教你用CSS實作表單部件
