網(wǎng)站首頁 編程語言 正文
AJAX 介紹
AJAX其實(shí)就是異步的js和xml
通過ajax可以在瀏覽器中發(fā)送異步請求。
最大優(yōu)勢:無刷新獲取數(shù)據(jù)
優(yōu)點(diǎn):
1.可以無需刷新頁面與服務(wù)器進(jìn)行通信
2.允許根據(jù)用戶事件更新部分頁面內(nèi)容
當(dāng)然也存在其缺點(diǎn)問題:比如跨域問題等!
一.原生AJAX請求(GET)
由于get和post請求類似,原生代碼相比jQuery復(fù)雜一些:原生代碼演示get請求 jquery演示get和post請求
代碼中會(huì)出現(xiàn)node.js的相關(guān)代碼,比如express框架,對node.js不熟悉的同學(xué)可以先注重前端代碼
前端代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> GET 請求</title>
<style>
#result{
width: 100px;
height: 100px;
border: 1px solid pink;
}
</style>
</head>
<body>
<button class="btn">發(fā)送請求</button>
<div id="result"></div>
<script>
var btn=document.querySelector(".btn")
const result=document.getElementById("result")
btn.addEventListener("click",function(){
//1.創(chuàng)建對象
const xhr=new XMLHttpRequest()
//2.初始化 設(shè)置請求方法和url
xhr.open("GET","http://127.0.0.1:3000/server?a=100&b=200");//?后面是get請求加參數(shù)方法
//3.發(fā)送
xhr.send()
//4.事件綁定 處理服務(wù)端返回的結(jié)果
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
//判斷響應(yīng)狀態(tài)碼
if(xhr.status>=200 && xhr.status<=300){
console.log(xhr.status);//狀態(tài)碼
console.log(xhr.statusText);//狀態(tài)字符串
console.log(xhr.getAllResponseHeaders());//所有響應(yīng)頭
console.log(xhr.response);//響應(yīng)體
result.innerHTML=xhr.response//把響應(yīng)結(jié)果給div盒子
}
}
}
})
</script>
</body>
</html>
服務(wù)端代碼
const express=require("express")
const app = express();
//1.對應(yīng)get請求
app.get("/server",(req,res)=>{
//設(shè)置響應(yīng)頭
res.setHeader("Access-Control-Allow-Origin","*")
//這里設(shè)置響應(yīng)頭允許所有域都具有訪問資源的權(quán)限。
//不設(shè)置就存在跨域問題,訪問不到,后面我們會(huì)介紹另外一種比較簡單的解決方法
//設(shè)置響應(yīng)體
res.send("hello GET-AJAX")
})
app.listen(3000,()=>{
console.log("服務(wù)啟動(dòng)");
})
二.jQuery AJAX請求(GET 和POST)
先了解一下jQuery中AJAXGET請求和POST請求語法:
get 請求
$.get(url, [data], [callback], [type])
url:請求的 URL 地址。
data:請求攜帶的參數(shù)。
callback:載入成功時(shí)回調(diào)函數(shù)。
type:設(shè)置返回內(nèi)容格式,xml, html, script, json, text,_default。
post 請求
$.post(url, [data], [callback], [type])
url:請求的 URL 地址。
data:請求攜帶的參數(shù)。
callback:載入成功時(shí)回調(diào)函數(shù)。
type:設(shè)置返回內(nèi)容格式,xml, html, script, json, text,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>jQuery 發(fā)送 AJAX 請求</title>
<script
crossorigin="anonymous"
src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"
></script>
</head>
<body>
<button >GET</button>
<button >POST</button>
<script>
//jQuery發(fā)送AJAX請求 -get請求
$("button").eq(0).click(function () {
$.get("http://127.0.0.1:5000/jquery-server", { a: 1, b: 2 }, (data) => {
console.log(data);
},"json"
);
});
//jQuery發(fā)送AJAX請求 -post請求
$("button").eq(1).click(function () {
$.post( "http://127.0.0.1:5000/jquery-server", { a: 1, b: 2 },(data) => {
console.log(data);
}, "json"
);
});
</script>
</body>
</html>
服務(wù)端代碼:
這里使用app.all()使得所有請求方法都可以訪問
const express = require('express');
const app = express();
//jQuery 服務(wù) 這里使用app.all()使得所有請求方法都可以訪問
app.all('/jquery-server', (request, response) => {
//設(shè)置響應(yīng)頭 設(shè)置允許跨域
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Headers', '*');
// response.send('Hello jQuery AJAX get');
const data = {name:'小吳同學(xué)'};
response.send(JSON.stringify(data));
});
//4. 監(jiān)聽端口啟動(dòng)服務(wù)
app.listen(5000, () => {
console.log("服務(wù)啟動(dòng)");
});
三.跨域問題的解決
跨域問題:當(dāng)我們的瀏覽器從一個(gè)域名的網(wǎng)頁去請求另一個(gè)域名的資源時(shí),其中域名、端口、協(xié)議任一不同,都是屬于跨域
示范例子
前端請求代碼如下 :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CORS</title>
<style>
#result{
width:200px;
height:100px;
border:solid 1px pink;
}
</style>
</head>
<body>
<button class="btn">發(fā)送請求</button>
<div id="result"></div>
<script>
const btn = document.querySelector('.btn');
btn.onclick = function(){
const xhr = new XMLHttpRequest();
xhr.open("GET", "http://127.0.0.1:5000/server");
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
//輸出響應(yīng)體
console.log(xhr.response);
result.innerHTML=xhr.response
}
}
}
}
</script>
</body>
</html>
服務(wù)端我介紹兩種簡單且效率極高的方法解決跨域問題
1.在服務(wù)端設(shè)置header
const express = require('express');
const app = express();
app.all('/server', (request, response)=>{
//設(shè)置響應(yīng)頭方法
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", '*');
response.setHeader("Access-Control-Allow-Method", '*');
response.send('設(shè)置響應(yīng)頭解決跨域問題成功');
});
app.listen(5000, () => {
console.log("服務(wù)啟動(dòng)");
});
2.使用中間件cors
const express = require('express');
const app = express();
//使用cors中間件方法
const cors=require("cors")
app.use(cors())
app.all('/server', (request, response)=>{
response.send('使用cors中間件解決跨域問題成功');
});
app.listen(5000, () => {
console.log("服務(wù)啟動(dòng)");
});
這里給大家具體講一下cors中間件使用步驟
1.在終端使用 npm i cors 命令下載這個(gè)中間件
2.使用require導(dǎo)入cors中間件:const cors=require(“cors”)
3.用app.use()方法注冊中間件:app.use(cors()) 注意:這個(gè)注冊方法一定要寫在在配置路由之前
四.其他解決跨域問題方法
一.JSONP跨域
JSONP(JSON with Padding),是一個(gè)非官方的跨域解決方案,只支持get請求(具有局限性)
工作原理:JSONP 就是利用 script 標(biāo)簽的跨域能力來發(fā)送請求的。
二.nginx反向代理
大致解釋:
www.A.com/index.html需要調(diào)用www.B.com/server.js,可以寫一個(gè)中間接口www.A.com/server.js,靠著這個(gè)接口在服務(wù)端
去調(diào)用www.B.com/server.js并拿到返回值,然后再返回給index.html
這個(gè)方法一般很少使用,它可以不用目標(biāo)服務(wù)器與前端配合,但是需要搭建一個(gè)中轉(zhuǎn)nginx服務(wù)器,用于轉(zhuǎn)發(fā)請求。
總結(jié)
原文鏈接:https://blog.csdn.net/xiaowuwjw/article/details/122814302
相關(guān)推薦
- 2021-12-16 .NET?Core配置TLS?Cipher(套件)的詳細(xì)過程_實(shí)用技巧
- 2024-01-30 MongoDB 聚合查詢在數(shù)據(jù)統(tǒng)計(jì)中的應(yīng)用
- 2022-04-04 webpack-loaders: postcss
- 2022-03-28 Python獲取網(wǎng)絡(luò)時(shí)間戳的兩種方法詳解_python
- 2022-11-10 golang?常用定時(shí)任務(wù)匯總_Golang
- 2023-03-17 C語言編程實(shí)例之輸出指定圖形問題_C 語言
- 2022-03-17 c++智能指針unique_ptr的使用_C 語言
- 2023-06-13 react實(shí)現(xiàn)組件狀態(tài)緩存的示例代碼_React
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支