AJAX請求以及解決跨域問題詳解
目錄
- AJAX 介紹
- 一.原生AJAX請求(GET)
- 二.jQuery AJAX請求(GET 和POST)
- 三.跨域問題的解決
- 四.其他解決跨域問題方法
- 總結(jié)
AJAX 介紹
AJAX其實就是異步的js和xml
通過ajax可以在瀏覽器中發(fā)送異步請求。
最大優(yōu)勢:無刷新獲取數(shù)據(jù)
優(yōu)點:
1.可以無需刷新頁面與服務(wù)器進(jìn)行通信
2.允許根據(jù)用戶事件更新部分頁面內(nèi)容
當(dāng)然也存在其缺點問題:比如跨域問題等!
一.原生AJAX請求(GET)
由于get和post請求類似,原生代碼相比jQuery復(fù)雜一些:原生代碼演示get請求 jquery演示get和post請求
代碼中會出現(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>發(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è)置就存在跨域問題,訪問不到,后面我們會介紹另外一種比較簡單的解決方法
//設(shè)置響應(yīng)體
res.send("hello GET-AJAX")
})
app.listen(3000,()=>{
console.log("服務(wù)啟動");
})
二.jQuery AJAX請求(GET 和POST)
先了解一下jQuery中AJAXGET請求和POST請求語法:
get 請求
$.get(url, [data], [callback], [type])
url:請求的 URL 地址。
data:請求攜帶的參數(shù)。
callback:載入成功時回調(diào)函數(shù)。
type:設(shè)置返回內(nèi)容格式,xml, html, script, json, text,_default。
post 請求
$.post(url, [data], [callback], [type])
url:請求的 URL 地址。
data:請求攜帶的參數(shù)。
callback:載入成功時回調(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)聽端口啟動服務(wù)
app.listen(5000, () => {
console.log("服務(wù)啟動");
});
三.跨域問題的解決
跨域問題:當(dāng)我們的瀏覽器從一個域名的網(wǎng)頁去請求另一個域名的資源時,其中域名、端口、協(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>發(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ù)啟動");
});
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ù)啟動");
});
這里給大家具體講一下cors中間件使用步驟
1.在終端使用 npm i cors 命令下載這個中間件
2.使用require導(dǎo)入cors中間件:const cors=require(“cors”)
3.用app.use()方法注冊中間件:app.use(cors()) 注意:這個注冊方法一定要寫在在配置路由之前
四.其他解決跨域問題方法
一.JSONP跨域
JSONP(JSON with Padding),是一個非官方的跨域解決方案,只支持get請求(具有局限性)
工作原理:JSONP 就是利用 script 標(biāo)簽的跨域能力來發(fā)送請求的。
二.nginx反向代理
大致解釋:
www.A.com/index.html需要調(diào)用www.B.com/server.js,可以寫一個中間接口www.A.com/server.js,靠著這個接口在服務(wù)端
去調(diào)用www.B.com/server.js并拿到返回值,然后再返回給index.html
這個方法一般很少使用,它可以不用目標(biāo)服務(wù)器與前端配合,但是需要搭建一個中轉(zhuǎn)nginx服務(wù)器,用于轉(zhuǎn)發(fā)請求。
總結(jié)
到此這篇關(guān)于AJAX請求以及解決跨域問題的文章就介紹到這了,更多相關(guān)AJAX請求及解決跨域內(nèi)容請搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!
相關(guān)文章:

網(wǎng)公網(wǎng)安備