AJAX請(qǐng)求以及解決跨域問題詳解
目錄
- AJAX 介紹
- 一.原生AJAX請(qǐng)求(GET)
- 二.jQuery AJAX請(qǐng)求(GET 和POST)
- 三.跨域問題的解決
- 四.其他解決跨域問題方法
- 總結(jié)
AJAX 介紹
AJAX其實(shí)就是異步的js和xml
通過ajax可以在瀏覽器中發(fā)送異步請(qǐng)求。
最大優(yōu)勢:無刷新獲取數(shù)據(jù)
優(yōu)點(diǎn):
1.可以無需刷新頁面與服務(wù)器進(jìn)行通信
2.允許根據(jù)用戶事件更新部分頁面內(nèi)容
當(dāng)然也存在其缺點(diǎn)問題:比如跨域問題等!
一.原生AJAX請(qǐng)求(GET)
由于get和post請(qǐng)求類似,原生代碼相比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>發(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)頭允許所有域都具有訪問資源的權(quán)限。 //不設(shè)置就存在跨域問題,訪問不到,后面我們會(huì)介紹另外一種比較簡單的解決方法 //設(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)求語法:
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)求方法都可以訪問
const express = require("express"); const app = express(); //jQuery 服務(wù) 這里使用app.all()使得所有請(qǐng)求方法都可以訪問 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)頁去請(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>發(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ù)端我介紹兩種簡單且效率極高的方法解決跨域問題
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()方法注冊(cè)中間件:app.use(cors()) 注意:這個(gè)注冊(cè)方法一定要寫在在配置路由之前
四.其他解決跨域問題方法
一.JSONP跨域
JSONP(JSON with Padding),是一個(gè)非官方的跨域解決方案,只支持get請(qǐng)求(具有局限性)
工作原理:JSONP 就是利用 script 標(biāo)簽的跨域能力來發(fā)送請(qǐng)求的。
二.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ā)請(qǐng)求。
總結(jié)
到此這篇關(guān)于AJAX請(qǐng)求以及解決跨域問題的文章就介紹到這了,更多相關(guān)AJAX請(qǐng)求及解決跨域內(nèi)容請(qǐng)搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!
相關(guān)文章:
