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