六、jQuery 中的 AJAX 跨域问题
生活随笔
收集整理的這篇文章主要介紹了
六、jQuery 中的 AJAX 跨域问题
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
第 2 章:jQuery 中的 AJAX
官方中文文檔:https://jquery.cuishifeng.cn/jQuery.Ajax.html
2.1 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。
2.2 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, _default。
代碼演示:
<!DOCTYPE html> <html><head><meta charset="utf-8"><title>jQuery發(fā)送AJAX請(qǐng)求</title><link rel="stylesheet" href="../bootstrap-4.6.0-dist/css/bootstrap.min.css"></head><body><div class="container"><h2 class="page-header">jQuery發(fā)送AJAX請(qǐng)求</h2><button type="button" class="btn btn-primary">GET</button><button type="button" class="btn btn-danger">POST</button><button type="button" class="btn btn-info">通用型方法</button></div><script src="../bootstrap-4.6.0-dist/js/jquery.min.js"></script><script src="../bootstrap-4.6.0-dist/js/bootstrap.bundle.min.js"></script><script type="text/javascript">$('button').eq(0).click(function() {$.get('http://127.0.0.1:8000/jquery-server', {a: 100,name: 'zep'}, function(data) {console.log(data)}, 'json')})$('button').eq(1).click(function() {$.post('http://127.0.0.1:8000/jquery-server', {a: 100,name: 'zep'}, function(data) {console.log(data)}, 'json')})$('button').eq(2).click(function() {$.ajax({// urlurl: 'http://127.0.0.1:8000/jquery-server',// 參數(shù)data: {a:100, name: 'zep'},// 請(qǐng)求類型type: 'GET',// 響應(yīng)體結(jié)果dataType: 'json',// 成功的回調(diào)success: function(data) {console.log(data)},// 超時(shí)時(shí)間timeout: 2000,// 失敗的回調(diào)error: function() {console.log('出錯(cuò)啦!!!')},// 頭信息headers: {c: 300,d: 400}})})</script></body> </html>server.js:
// 1. 引入express const express = require('express')// 2. 創(chuàng)建應(yīng)用對(duì)象 const app = express()// 3. 創(chuàng)建路由規(guī)則 app.get('/server', (request, response) => {// 設(shè)置響應(yīng)頭 設(shè)置允許跨域response.setHeader('Access-Control-Allow-Origin', '*')// 設(shè)置響應(yīng)體response.send('hello ajax!!!') })// all 可以接收任意類型的請(qǐng)求 app.all('/server', (request, response) => {// 設(shè)置響應(yīng)頭 設(shè)置允許跨域response.setHeader('Access-Control-Allow-Origin', '*')// 允許前端post請(qǐng)求 自定義請(qǐng)求頭名稱response.header('Access-Control-Allow-Headers', '*');// 設(shè)置響應(yīng)體response.send('hello ajax post') })app.all('/json-server', (request, response) => {// 設(shè)置響應(yīng)頭 設(shè)置允許跨域response.setHeader('Access-Control-Allow-Origin', '*')// 允許前端post請(qǐng)求 自定義請(qǐng)求頭名稱response.header('Access-Control-Allow-Headers', '*');// 響應(yīng)一個(gè)數(shù)據(jù)const data = {name: 'zep'};// 對(duì) 對(duì)象進(jìn)行字符串轉(zhuǎn)換let str = JSON.stringify(data)// 設(shè)置響應(yīng)體,send方法只接收字符串類型的參數(shù)response.send(str) })// 專門針對(duì)IE緩存 app.get('/ie', (request, response) => {// 設(shè)置響應(yīng)頭 設(shè)置允許跨域response.setHeader('Access-Control-Allow-Origin', '*')// 設(shè)置響應(yīng)體response.send('hello ie3!!!') })// 延時(shí)響應(yīng) app.get('/delay', (request, response) => {// 設(shè)置響應(yīng)頭 設(shè)置允許跨域response.setHeader('Access-Control-Allow-Origin', '*')// 設(shè)置定時(shí)器,當(dāng)客戶端發(fā)起請(qǐng)求時(shí),服務(wù)端延遲3s再將響應(yīng)數(shù)據(jù)發(fā)給客戶端setTimeout(() => {// 設(shè)置響應(yīng)體response.send('hello 延遲響應(yīng)3秒!!!')}, 3000)})// jQuery服務(wù) app.all('/jquery-server', (request, response) => {// 設(shè)置響應(yīng)頭 設(shè)置允許跨域response.setHeader('Access-Control-Allow-Origin', '*')// 允許前端post請(qǐng)求 自定義請(qǐng)求頭名稱response.header('Access-Control-Allow-Headers', '*');// 設(shè)置響應(yīng)體const data = {name: 'zep'}// response.send('hello jquery ajax!')response.send(JSON.stringify(data)) })// 4. 監(jiān)聽端口 啟動(dòng)服務(wù) app.listen(8000, () => {console.log('服務(wù)已經(jīng)啟動(dòng),8000端口監(jiān)聽中...') })第3章: axios
官方中文文檔:http://www.axios-js.com/zh-cn/docs/
使用方法:
第一種:
cdn引入: https://www.bootcdn.cn/axios/
第二種:
npm install axios
代碼演示:
axios.html :
<!DOCTYPE html> <html><head><meta charset="utf-8"><title>axios 發(fā)送ajax請(qǐng)求</title></head><body><button>GET</button><button>POST</button><button>AJAX</button><script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script><script>const btns = document.querySelectorAll('button');// 配置baseURLaxios.defaults.baseURL = 'http://127.0.0.1:8000'btns[0].onclick = function() {// GET 請(qǐng)求axios.get('/axios-server', {// url參數(shù)params: {id: 100,vip: 7},// 請(qǐng)求頭信息headers: {name: 'zep',age: 22}}).then(value => {console.log(value)})}btns[1].onclick = function() {// POST請(qǐng)求axios.post('/axios-server',// 請(qǐng)求體{username: 'admin',password: 'admin'}, {params: {id: 200,vip: 10},// 請(qǐng)求頭信息headers: {name: 'zep111',age: 22}})}btns[2].onclick = function() {axios({// 請(qǐng)求方法method: 'POST',// urlurl: '/axios-server',// url參數(shù)params: {vip: 20,level: 30},//頭信息headers: {a: 100,b: 200},//請(qǐng)求體參數(shù)data: {username: 'admin',password: 'admin'}}).then(response => {console.log(response)// 響應(yīng)狀態(tài)碼console.log(response.status)// 響應(yīng)狀態(tài)字符串console.log(response.statusText)// 響應(yīng)頭信息console.log(response.headers)// 響應(yīng)體console.log(response.data)})}</script></body> </html>server.js:
// 1. 引入express const express = require('express')// 2. 創(chuàng)建應(yīng)用對(duì)象 const app = express()// 3. 創(chuàng)建路由規(guī)則 app.get('/server', (request, response) => {// 設(shè)置響應(yīng)頭 設(shè)置允許跨域response.setHeader('Access-Control-Allow-Origin', '*')// 設(shè)置響應(yīng)體response.send('hello ajax!!!') })// all 可以接收任意類型的請(qǐng)求 app.all('/server', (request, response) => {// 設(shè)置響應(yīng)頭 設(shè)置允許跨域response.setHeader('Access-Control-Allow-Origin', '*')// 允許前端post請(qǐng)求 自定義請(qǐng)求頭名稱response.header('Access-Control-Allow-Headers', '*');// 設(shè)置響應(yīng)體response.send('hello ajax post') })app.all('/json-server', (request, response) => {// 設(shè)置響應(yīng)頭 設(shè)置允許跨域response.setHeader('Access-Control-Allow-Origin', '*')// 允許前端post請(qǐng)求 自定義請(qǐng)求頭名稱response.header('Access-Control-Allow-Headers', '*');// 響應(yīng)一個(gè)數(shù)據(jù)const data = {name: 'zep'};// 對(duì) 對(duì)象進(jìn)行字符串轉(zhuǎn)換let str = JSON.stringify(data)// 設(shè)置響應(yīng)體,send方法只接收字符串類型的參數(shù)response.send(str) })// 專門針對(duì)IE緩存 app.get('/ie', (request, response) => {// 設(shè)置響應(yīng)頭 設(shè)置允許跨域response.setHeader('Access-Control-Allow-Origin', '*')// 設(shè)置響應(yīng)體response.send('hello ie3!!!') })// 延時(shí)響應(yīng) app.get('/delay', (request, response) => {// 設(shè)置響應(yīng)頭 設(shè)置允許跨域response.setHeader('Access-Control-Allow-Origin', '*')// 設(shè)置定時(shí)器,當(dāng)客戶端發(fā)起請(qǐng)求時(shí),服務(wù)端延遲3s再將響應(yīng)數(shù)據(jù)發(fā)給客戶端setTimeout(() => {// 設(shè)置響應(yīng)體response.send('hello 延遲響應(yīng)3秒!!!')}, 3000)})// jQuery服務(wù) app.all('/jquery-server', (request, response) => {// 設(shè)置響應(yīng)頭 設(shè)置允許跨域response.setHeader('Access-Control-Allow-Origin', '*')// 允許前端post請(qǐng)求 自定義請(qǐng)求頭名稱response.header('Access-Control-Allow-Headers', '*');// 設(shè)置響應(yīng)體const data = {name: 'zep'}// response.send('hello jquery ajax!')response.send(JSON.stringify(data)) })// axios服務(wù) app.all('/axios-server', (request, response) => {// 設(shè)置響應(yīng)頭 設(shè)置允許跨域response.setHeader('Access-Control-Allow-Origin', '*')// 允許前端post請(qǐng)求 自定義請(qǐng)求頭名稱response.header('Access-Control-Allow-Headers', '*');// 設(shè)置響應(yīng)體const data = {name: 'zep-axios'}// response.send('hello jquery ajax!')response.send(JSON.stringify(data)) })// 4. 監(jiān)聽端口 啟動(dòng)服務(wù) app.listen(8000, () => {console.log('服務(wù)已經(jīng)啟動(dòng),8000端口監(jiān)聽中...') })第4章: fetch()發(fā)送Ajax請(qǐng)求:
參考文檔:https://developer.mozilla.org/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/fetch
第 45章:跨域
3.1 同源策略
同源策略(Same-Origin Policy)最早由 Netscape 公司提出,是瀏覽器的一種安全策略。
- 同源: 協(xié)議、域名、端口號(hào) 必須完全相同。
- 違背同源策略就是跨域。
代碼演示:
<!DOCTYPE html> <html><head><meta charset="utf-8"><title>首頁(yè)</title></head><body><h1>我愛(ài)ajax</h1><button>點(diǎn)擊獲取用戶數(shù)據(jù)</button><script>const btn = document.querySelector('button')btn.onclick = function () {const xhr = new XMLHttpRequest();// 這里因?yàn)闀r(shí)滿足同源策略的,所以u(píng)rl可以簡(jiǎn)寫xhr.open('GET', '/data');// 發(fā)送xhr.send();xhr.onreadystatechange = function () {if(xhr.readyState === 4) {if(xhr.status >= 200 && xhr.status < 300) {console.log(xhr.response);}}}}</script></body> </html>server.js :
const express = require('express')const app = express();app.get('/home', (request, response) => {// 響應(yīng)一個(gè)頁(yè)面response.sendFile(__dirname + '/index.html');});app.get('/data', (request, response) => {response.send('用戶數(shù)據(jù)。。。') })app.listen(9000, () => {console.log('服務(wù)已經(jīng)啟動(dòng)。。。,監(jiān)聽9000端口!!!') })
3.2 如何解決跨域
3.2.1 JSONP
JSONP 就是利用 script 標(biāo)簽的跨域能力來(lái)發(fā)送請(qǐng)求的。
1.動(dòng)態(tài)的創(chuàng)建一個(gè) script 標(biāo)簽
4.服務(wù)器中路由的處理
router.get("/testAJAX" , function (req , res) { console.log("收到請(qǐng)求"); var callback = req.query.callback; var obj = {name:"孫悟空", age:18 }res.send(callback+"("+JSON.stringify(obj)+")"); });代碼演示
2. 原生jsonp實(shí)踐:
3. jQuery 發(fā)送 jsonp實(shí)踐:
3.2.2 CORS
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
CORS(Cross-Origin Resource Sharing),跨域資源共享。CORS 是官方的跨域解決方 案,它的特點(diǎn)是不需要在客戶端做任何特殊的操作,完全在服務(wù)器中進(jìn)行處理,支持 get 和 post 請(qǐng)求。跨域資源共享標(biāo)準(zhǔn)新增了一組 HTTP 首部字段,允許服務(wù)器聲明哪些 源站通過(guò)瀏覽器有權(quán)限訪問(wèn)哪些資源
CORS 是通過(guò)設(shè)置一個(gè)響應(yīng)頭來(lái)告訴瀏覽器,該請(qǐng)求允許跨域,瀏覽器收到該響應(yīng) 以后就會(huì)對(duì)響應(yīng)放行。
總結(jié)
以上是生活随笔為你收集整理的六、jQuery 中的 AJAX 跨域问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 八、Vue cli3详解学习笔记
- 下一篇: uni-ui介绍uni-api