7 Ajax
簡介
-
AJAX = Asynchronous JavaScript and XML(異步的 JavaScript 和 XML),
-
AJAX 是一種在無需重新加載整個網頁的情況下,能夠更新部分網頁的技術,
-
Ajax 不是一種新的編程語言,而是一種用于創建更好更快以及互動性更強的Web應用程式的技術,
-
在 2005 年,Google 通過其 Google Suggest 使 AJAX 變得流行起來,Google Suggest能夠自動幫你完成搜索單詞,
-
Google Suggest 使用 AJAX 創造出動態性極強的 web 界面:當您在谷歌的搜索框輸入關鍵字時,JavaScript 會把這些字符發送到服務器,然后服務器會回傳一個搜索建議的串列,
-
傳統的網頁(即不使用ajax技術的網頁),想要更新內容或者提交一個表單,都需要重新加載整個網頁,
-
使用ajax技術的網頁,通過在后臺服務器進行少量的資料交換,就可以實作異步區域更新,
-
使用Ajax,用戶可以創建接近本地桌面應用的直接、高可用、更豐富、更動態的Web用戶界面,
偽造Ajax
1、新建module springmvc-06-ajax,匯入web支持,測驗專案,是否能成功運行!
2、撰寫一個 test.html 使用 iframe測驗
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>偽造AJAX</title>
</head>
<body>
<script type="text/javascript">
window.onload = function(){
var myDate = new Date();
document.getElementById('currentTime').innerText = myDate.getTime();
};
function LoadPage(){
var targetUrl = document.getElementById('url').value;
console.log(targetUrl);
document.getElementById("iframePosition").src = https://www.cnblogs.com/zzbstudy/p/targetUrl;
}
</script>
請輸入要加載的地址:
3、在IDEA中打開瀏覽器查看效果!

利用AJAX可以做:
- 注冊時,檢測用戶名是否已注冊
- 登錄時,提示用戶名密碼錯誤
- 等等
jQuery.ajax
-
這里使用jquery來實作ajax;
-
Ajax的核心是XMLHttpRequest物件(XHR),XHR為向服務器發送請求和決議服務器回應提供了介面,能夠以異步方式從服務器獲取新資料;
-
jQuery 提供多個與 AJAX 有關的方法;
-
通過jQuery.AJAX方法,可以使用HTTP GET 何HTTP POST從遠程服務器上請求文本、HTML、XML活JSON,同時也可以把這些外部資料直接載入網頁的被選元素中;
-
jQuery 不是生產者,而是大自然搬運工;
-
jQuery Ajax本質就是 XMLHttpRequest,對他進行了封裝,方便呼叫!
jQuery.ajax(...)
部分引數:
url:請求地址
type:請求方式,GET、POST(1.9.0之后用method)
headers:請求頭
data:要發送的資料
contentType:即將發送資訊至服務器的內容編碼型別(默認: "application/x-www-form-urlencoded; charset=UTF-8")
async:是否異步
timeout:設定請求超時時間(毫秒)
beforeSend:發送請求前執行的函式(全域)
complete:完成之后執行的回呼函式(全域)
success:成功之后執行的回呼函式(全域)
error:失敗之后執行的回呼函式(全域)
accepts:通過請求頭發送給服務器,告訴服務器當前客戶端可接受的資料型別
dataType:將服務器端回傳的資料轉換成指定型別
"xml": 將服務器端回傳的內容轉換成xml格式
"text": 將服務器端回傳的內容轉換成普通文本格式
"html": 將服務器端回傳的內容轉換成普通文本格式,在插入DOM中時,如果包含JavaScript標簽,則會嘗試去執行,
"script": 嘗試將回傳值當作JavaScript去執行,然后再將服務器端回傳的內容轉換成普通文本格式
"json": 將服務器端回傳的內容轉換成相應的JavaScript物件
"jsonp": JSONP 格式使用 JSONP 形式呼叫函式時,如 "myurl?callback=?" jQuery 將自動替換 ? 為正確的函式名,以執行回呼函式
使用 HttpServletResponse 處理,實作簡單的測驗!
1、配置 web.xml 和 springmvc 的組態檔,
2、撰寫一個AjaxController
package com.zzb.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
public class AjaxController {
@RequestMapping("/a1")
public void a1(String name, HttpServletResponse response) throws IOException {
System.out.println("a1:param=>" + name);
if("admin".equals(name)){
response.getWriter().print("true");
}else{
response.getWriter().print("false");
}
}
}
3、撰寫index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<%--匯入在線jquery--%>
<script src="https://www.cnblogs.com/zzbstudy/p/${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
<script>
function a(){
$.post({
url:"${pageContext.request.contextPath}/a1",
data:{'name':$("#txtName").val()},
success:function (data){
alert(data);
}
});
}
</script>
</head>
<body>
<%--失去焦點觸發事件--%>
用戶名:<input type="text" id="txtName" onblur="a()">
</body>
</html>
4、啟動tomcat測驗

SpringMVC實作
1、物體類
package com.zzb.pojo;
public class User {
private String name;
private int age;
private String sex;
public User() {
}
public User(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
}
2、Controller類撰寫
@RequestMapping("/a2")
public List<User> a2(){
List<User> userList = new ArrayList<User>();
userList.add(new User("Zzb1號",1,"男"));
userList.add(new User("Zzb2號",2,"男"));
userList.add(new User("Zzb3號",3,"男"));
return userList; // 由于@RestController注解,將list轉成json格式回傳
}
3、前端頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="https://www.cnblogs.com/zzbstudy/p/${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
</head>
<body>
<input type="button" id="btn" value="https://www.cnblogs.com/zzbstudy/p/獲取資料"/>
<table width="80%" align="center">
<tr>
<td>姓名</td>
<td>年齡</td>
<td>性別</td>
</tr>
<tbody id="content">
</tbody>
</table>
<script>
$("#btn").click(function (){
$.post("${pageContext.request.contextPath}/a2", function (data){
console.log(data)
var html = "";
for(var i = 0; i < data.length; ++i){
html+="<tr>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].age + "</td>" + "<td>" + data[i].sex + "</td>" + "</tr>"
}
$("#content").html(html);
})
})
</script>
</body>
</html>
4、測驗

注冊提示效果
1、撰寫Controller類
@RequestMapping("/a3")
public String a3(String name){
String msg = "";
// 模擬資料庫中存在資料
if(name != null){
if("admin".equals(name)){
msg = "ok";
}else{
msg = "用戶名不存在!";
}
}
return msg;
}
2、前端頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="https://www.cnblogs.com/zzbstudy/p/${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
</head>
<body>
<p>
用戶名:<input type="text" id="name" onblur="a()">
<span id="userInfo"></span>
</p>
<p>
密碼:<input type="password" id="pwd" onblur="a()">
</p>
<script>
function a(){
$.post({
url:"${pageContext.request.contextPath}/a3",
data:{'name':$("#name").val()},
success:function (data){
console.log(data);
if(data.toString() == "ok"){
$("#userInfo").css("color", "green");
}else{
$("#userInfo").css("color", "red");
}
$("#userInfo").html(data);
}
});
}
</script>
</body>
</html>
注意:因為傳遞的是json物件,所以要處理json字串的亂碼問題
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean >
<constructor-arg value="https://www.cnblogs.com/zzbstudy/p/UTF-8"/>
</bean>
<bean >
<property name="objectMapper">
<bean >
<property name="failOnEmptyBeans" value="https://www.cnblogs.com/zzbstudy/p/false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
3、測驗


獲取百度介面Demo
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>JSONP百度搜索</title>
<style>
#q{
width: 500px;
height: 30px;
border:1px solid #ddd;
line-height: 30px;
display: block;
margin: 0 auto;
padding: 0 10px;
font-size: 14px;
}
#ul{
width: 520px;
list-style: none;
margin: 0 auto;
padding: 0;
border:1px solid #ddd;
margin-top: -1px;
display: none;
}
#ul li{
line-height: 30px;
padding: 0 10px;
}
#ul li:hover{
background-color: #f60;
color: #fff;
}
</style>
<script>
// 2.步驟二
// 定義demo函式 (分析介面、資料)
function demo(data){
var Ul = document.getElementById('ul');
var html = '';
// 如果搜索資料存在 把內容添加進去
if (data.s.length) {
// 隱藏掉的ul顯示出來
Ul.style.display = 'block';
// 搜索到的資料回圈追加到li里
for(var i = 0;i<data.s.length;i++){
html += '<li>'+data.s[i]+'</li>';
}
// 回圈的li寫入ul
Ul.innerHTML = html;
}
}
// 1.步驟一
window.onload = function(){
// 獲取輸入框和ul
var Q = document.getElementById('q');
// 事件滑鼠抬起時候
Q.onkeyup = function(){
// 如果輸入框不等于空
if (this.value != '') {
// ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆JSONPz重點☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆
// 創建標簽
var script = document.createElement('script');
//給定要跨域的地址 賦值給src
//這里是要請求的跨域的地址 我寫的是百度搜索的跨域地址
//&cb=demo ---》 會回傳 demo(data)
script.src = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+this.value+'&cb=demo';
// 將組合好的帶src的script標簽追加到body里
document.body.appendChild(script);
}
}
}
</script>
</head>
<body>
<input type="text" id="q" />
<ul id="ul">
</ul>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/245519.html
標籤:Java
下一篇:組合與繼承
