網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
AJAX 介紹
AJAX其實(shí)就是異步的js和xml
通過(guò)ajax可以在瀏覽器中發(fā)送異步請(qǐng)求。
最大優(yōu)勢(shì):無(wú)刷新獲取數(shù)據(jù)
優(yōu)點(diǎn):
1.可以無(wú)需刷新頁(yè)面與服務(wù)器進(jìn)行通信
2.允許根據(jù)用戶事件更新部分頁(yè)面內(nèi)容
當(dāng)然也存在其缺點(diǎn)問(wèn)題:比如跨域問(wèn)題等!
一.原生AJAX請(qǐng)求(GET)
由于get和post請(qǐng)求類(lèi)似,原生代碼相比jQuery復(fù)雜一些:原生代碼演示get請(qǐng)求 jquery演示get和post請(qǐng)求
代碼中會(huì)出現(xiàn)node.js的相關(guān)代碼,比如express框架,對(duì)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 請(qǐng)求</title>
<style>
#result{
width: 100px;
height: 100px;
border: 1px solid pink;
}
</style>
</head>
<body>
<button class="btn">發(fā)送請(qǐng)求</button>
<div id="result"></div>
<script>
var btn=document.querySelector(".btn")
const result=document.getElementById("result")
btn.addEventListener("click",function(){
//1.創(chuàng)建對(duì)象
const xhr=new XMLHttpRequest()
//2.初始化 設(shè)置請(qǐng)求方法和url
xhr.open("GET","http://127.0.0.1:3000/server?a=100&b=200");//?后面是get請(qǐng)求加參數(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.對(duì)應(yīng)get請(qǐng)求
app.get("/server",(req,res)=>{
//設(shè)置響應(yīng)頭
res.setHeader("Access-Control-Allow-Origin","*")
//這里設(shè)置響應(yīng)頭允許所有域都具有訪問(wèn)資源的權(quán)限。
//不設(shè)置就存在跨域問(wèn)題,訪問(wèn)不到,后面我們會(huì)介紹另外一種比較簡(jiǎn)單的解決方法
//設(shè)置響應(yīng)體
res.send("hello GET-AJAX")
})
app.listen(3000,()=>{
console.log("服務(wù)啟動(dòng)");
})
二.jQuery AJAX請(qǐng)求(GET 和POST)
先了解一下jQuery中AJAXGET請(qǐng)求和POST請(qǐng)求語(yǔ)法:
get 請(qǐng)求
$.get(url, [data], [callback], [type])
url:請(qǐng)求的 URL 地址。
data:請(qǐng)求攜帶的參數(shù)。
callback:載入成功時(shí)回調(diào)函數(shù)。
type:設(shè)置返回內(nèi)容格式,xml, html, script, json, text,_default。
post 請(qǐng)求
$.post(url, [data], [callback], [type])
url:請(qǐng)求的 URL 地址。
data:請(qǐng)求攜帶的參數(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 請(qǐng)求</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請(qǐng)求 -get請(qǐng)求
$("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請(qǐng)求 -post請(qǐng)求
$("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()使得所有請(qǐng)求方法都可以訪問(wèn)
const express = require('express');
const app = express();
//jQuery 服務(wù) 這里使用app.all()使得所有請(qǐng)求方法都可以訪問(wèn)
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)聽(tīng)端口啟動(dòng)服務(wù)
app.listen(5000, () => {
console.log("服務(wù)啟動(dòng)");
});
三.跨域問(wèn)題的解決
跨域問(wèn)題:當(dāng)我們的瀏覽器從一個(gè)域名的網(wǎng)頁(yè)去請(qǐng)求另一個(gè)域名的資源時(shí),其中域名、端口、協(xié)議任一不同,都是屬于跨域
示范例子
前端請(qǐng)求代碼如下 :
<!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ā)送請(qǐng)求</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ù)端我介紹兩種簡(jiǎn)單且效率極高的方法解決跨域問(wèn)題
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)頭解決跨域問(wèn)題成功');
});
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中間件解決跨域問(wèn)題成功');
});
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()方法注冊(cè)中間件:app.use(cors()) 注意:這個(gè)注冊(cè)方法一定要寫(xiě)在在配置路由之前
四.其他解決跨域問(wèn)題方法
一.JSONP跨域
JSONP(JSON with Padding),是一個(gè)非官方的跨域解決方案,只支持get請(qǐng)求(具有局限性)
工作原理:JSONP 就是利用 script 標(biāo)簽的跨域能力來(lái)發(fā)送請(qǐng)求的。
二.nginx反向代理
大致解釋?zhuān)?/p>
www.A.com/index.html需要調(diào)用www.B.com/server.js,可以寫(xiě)一個(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ā)請(qǐng)求。
總結(jié)
原文鏈接:https://blog.csdn.net/xiaowuwjw/article/details/122814302
相關(guān)推薦
- 2022-10-05 帶你深度走入C語(yǔ)言取整以及4種函數(shù)_C 語(yǔ)言
- 2022-06-18 C#使用Monitor類(lèi)實(shí)現(xiàn)線程同步_C#教程
- 2022-08-12 Qt實(shí)現(xiàn)拖動(dòng)單個(gè)控件移動(dòng)的示例代碼_C 語(yǔ)言
- 2022-06-20 React函數(shù)組件與類(lèi)組件使用及優(yōu)劣對(duì)比_React
- 2022-02-12 asp.net 報(bào)錯(cuò) “/”應(yīng)用程序中的服務(wù)器錯(cuò)誤。 String or binary data w
- 2023-07-31 解決el-tree數(shù)據(jù)回顯時(shí)子節(jié)點(diǎn)部分選中,父節(jié)點(diǎn)都全選中的坑
- 2022-05-10 通過(guò)addroutes動(dòng)態(tài)添加路由
- 2023-01-17 怎樣保存模型權(quán)重和checkpoint_python
- 最近更新
-
- 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)證過(guò)濾器
- Spring Security概述快速入門(mén)
- 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)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支