目錄
jQuery中的Ajax
請求超時與網(wǎng)絡異常處理
取消請求
Ajax請求—fetch()
跨域
jQuery中的Ajax
在jQuery中應該如何發(fā)送Ajax請求呢?看到這篇文章你就能大概了解到如何在jQuery中發(fā)送Ajax。
要想使用jQuery框架,肯定是需要引進jQuery資源的,有兩種方式,一種是將資源下載到本地,另一種是直接引入網(wǎng)站jQuery鏈接,推薦大家一個比較好用的網(wǎng)站:bootcdn 其網(wǎng)站致力于為許多像 Bootstrap、jQuery、Angular、Vuejs 一樣優(yōu)秀的前端開源項目提供穩(wěn)定、快速的免費 CDN 加速服務。
點擊相關需求,引入相關鏈接到HTML里面即可,請看如下操作:
<!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>Document</title>
<link rel="stylesheet" >
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h2 class="page-header">jQuery發(fā)送Ajax請求</h2>
<button class="btn btn-paimary">GET</button>
<button class="btn btn-danger">POST</button>
<button class="btn btn-info">通用型方法</button>
</div>
<script>
$('button').eq(0).click(function(){
// 參數(shù)分別是 url 參數(shù)對象 回調函數(shù) 響應體類型-json
$.get('http://127.0.0.1:8000/jquery',{a:100,b:200},function(data){
console.log(data);
},'json')//加了json返回的結果是一個對象
})
$('button').eq(1).click(function(){
$.post('http://127.0.0.1:8000/jquery',{a:100,b:200},function(data){
console.log(data);
})//不加json返回的結果是一個字符串
})
</script>
</body>
</html>
// 1.引入express
const { response } = require('express')
const express = require('express')
// 2.創(chuàng)建應用對象
const app = express()
// 3.jQuery服務
app.all('/jquery',(request,response)=>{
// 設置響應頭
response.setHeader('Access-Control-Allow-Origin','*')
// response.send('hello jQuery')
const data = {name:'張三'}
response.send(JSON.stringify(data))
})
// 4.監(jiān)聽端口啟動服務
app.listen(8000,()=>{
console.log('服務已經(jīng)啟動,8080端口監(jiān)聽中....');
})
這里借用了一點bootstarp樣式來修改一下CSS屬性,讓樣式更好看點。
上面講解了get和post請求操作,如果想單獨設置個性化強一點的Ajax請求操作,可以選擇通用型操作,代碼如下:
<!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>Document</title>
<link rel="stylesheet" >
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h2 class="page-header">jQuery發(fā)送Ajax請求</h2>
<button class="btn btn-paimary">GET</button>
<button class="btn btn-danger">POST</button>
<button class="btn btn-info">通用型方法</button>
</div>
<script>
$('button').eq(2).click(function(){
$.ajax({
// url
url:'http://127.0.0.1:8000/jquery',
// 參數(shù)
data:{a:100,b:200},
// 請求類型
type:'GET',
// 響應體結果設置
dataType:'json',
// 成功的回調
success:function(data){
console.log(data);
},
// 超時時間
timeout:2000,
// 失敗的回調
error:function(){
console.log('出錯了?。?);
},
// 頭信息
headers:{
c:300,
d:400
}
})
})
</script>
</body>
</html>
請求超時與網(wǎng)絡異常處理
請求超時:當我們進行服務器數(shù)據(jù)傳輸時因為網(wǎng)絡原因出現(xiàn)超時問題,我們設置超時規(guī)則來提示用戶網(wǎng)絡超時
<!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>Document</title>
<style>
#result {
width: 200px;
height: 100px;
border: 1px solid #008c8c;
}
</style>
</head>
<body>
<button>點擊發(fā)送請求</button>
<div id="result"></div>
<script>
const btn = document.querySelector('button')
const result = document.querySelector('#result')
btn.addEventListener('click',function(){
const xhr = new XMLHttpRequest()
// 超時2s設置取消
xhr.timeout = 2000
// 超時回調
xhr.ontimeout = function(){
alert('網(wǎng)絡異常,請稍后重試??!')
}
xhr.open('GET','http://127.0.0.1:8000/delay')
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
result.innerHTML = xhr.response
}
}
}
})
</script>
</body>
</html>
設置express服務
// 1.引入express
const { response } = require('express')
const express = require('express')
// 2.創(chuàng)建應用對象
const app = express()
// 3.延時響應
app.get('/delay',(request,response)=>{
// 設置響應頭
response.setHeader('Access-Control-Allow-Origin','*')
// 設置延時效果
setTimeout(()=>{
// 設置響應體
response.send('延時響應')
},3000)
})
// 4.監(jiān)聽端口啟動服務
app.listen(8000,()=>{
console.log('服務已經(jīng)啟動,8080端口監(jiān)聽中....');
})
網(wǎng)絡異常:訪問網(wǎng)站時,如果網(wǎng)絡突然斷掉,通過Ajax來提醒我們網(wǎng)絡斷開。
取消請求
既然Ajax可以請求數(shù)據(jù),那我們也可以將Ajax請求的數(shù)據(jù)取消也可以的,這里需要借助Ajax的一個屬性 abort 來進行操作。案例如下:
<!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>Document</title>
</head>
<body>
<button>點擊發(fā)送請求</button>
<button>點擊取消請求</button>
<script>
const btns = document.querySelectorAll('button')
// 將x設置為全局變量
let x = null
btns[0].addEventListener('click',function(){
x = new XMLHttpRequest()
x.open('GET','http://127.0.0.1:8000/delay')
x.send()
})
// 取消方法 abort
btns[1].addEventListener('click',function(){
x.abort()
})
</script>
</body>
</html>
當然我也設置一個延時服務來進行數(shù)據(jù)還沒有請求完就取消的過程。
取消重復請求
在日常瀏覽網(wǎng)頁中,可以由于一些網(wǎng)絡或其他原因導致用戶瘋狂的進行數(shù)據(jù)請求,這樣一來,用戶的數(shù)量一高請求的數(shù)據(jù)就很龐大,導致服務器承受不住這么大的流量,所以我們就要進行取消重復的操作來緩解服務器的壓力。操作過程如下:
<!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>Document</title>
</head>
<body>
<button>點擊發(fā)送請求</button>
<script>
const btns = document.querySelector('button')
// 將x設置為全局變量
let x = null
// 標識變量
let isSending = false
btns.addEventListener('click',function(){
// 判斷標識變量
if(isSending) x.abort()//如果正在發(fā)送,則取消該請求,創(chuàng)建一個新的請求
x = new XMLHttpRequest()
// 修改 標識變量的值
isSending = true
x.open('GET','http://127.0.0.1:8000/delay')
x.send()
x.onreadystatechange = function(){
if(x.readyState === 4){
// 修改標識變量
isSending = false
}
}
})
</script>
</body>
</html>
提供express服務
// 1.引入express
const { response } = require('express')
const express = require('express')
// 2.創(chuàng)建應用對象
const app = express()
// 3.延時響應
app.get('/delay',(request,response)=>{
// 設置響應頭
response.setHeader('Access-Control-Allow-Origin','*')
// 設置延時效果
setTimeout(()=>{
// 設置響應體
response.send('延時響應')
},3000)
})
// 4.監(jiān)聽端口啟動服務
app.listen(8000,()=>{
console.log('服務已經(jīng)啟動,8080端口監(jiān)聽中....');
})
Ajax請求—fetch()
fetch()方法用于發(fā)起獲取資源的請求,它返回一個promise,這個promise會在請求響應后被resolve,并傳回 response 對象。注意:fetch()方法的參數(shù)與request()構造器是一樣的。
<body>
<button>Ajax請求</button>
<script>
const btn = document.querySelector('button')
btn.addEventListener('click',function(){
fetch('http://127.0.0.1:8000/fetch',{
// 請求方法
method:'POST',
// 請求頭
headers:{
name:'zhangsan'
},
// 請求體
body:'username=admin&password=admin'
}).then(response=>{
return response.json()
}).then(response=>{
console.log(response);
})
})
</script>
</body>
// 1.引入express
const { response } = require('express')
const express = require('express')
// 2.創(chuàng)建應用對象
const app = express()
// 3.fetch服務
app.all('/fetch',(request,response)=>{
// 設置響應頭
response.setHeader('Access-Control-Allow-Origin','*')
response.setHeader('Access-Control-Allow-Headers','*')
// response.send('hello jQuery')
const data = {name:'張三'}
response.send(JSON.stringify(data))
})
// 4.監(jiān)聽端口啟動服務
app.listen(8000,()=>{
console.log('服務已經(jīng)啟動,8080端口監(jiān)聽中....');
})
跨域
同源策略(Same-Origin-Policy)最早由 Netscape 公司提出,是瀏覽器的一種安全策略。同源就是協(xié)議、域名、端口號必須完全相同,違背同源策略就是跨域。Ajax默認遵循同源策略。
<body>
<button>點擊獲取用戶數(shù)據(jù)</button>
<script>
const btn = document.querySelector('button')
btn.addEventListener('click',function(){
const x = new XMLHttpRequest()
// 因為是滿足同源策略的,所以url是可以簡寫的
x.open('GET','/data')
x.send()
x.onreadystatechange = function(){
if(x.readyState === 4){
if(x.status >= 200 && x.status <300){
console.log(x.response);
}
}
}
})
</script>
</body>
const { response, request } = require('express')
const express = require('express')
const app = express()
app.get('/home',(request,response)=>{
// 響應一個頁面
response.sendFile(__dirname+'/index.html')
})
app.get('/data',(request,response)=>{
response.send('用戶數(shù)據(jù)')
})
app.listen(9000,()=>{
console.log('9000端口開啟,服務已啟動...');
})
如何解決跨域:
JSONP,是一個非官方的跨域解決方案,由程序員開發(fā)出來,只支持get請求。在網(wǎng)頁中有一些標簽天生具有跨域能力,比如:img、link、iframe、script等,JSONP就是利用script標簽的跨域能力來發(fā)送請求的。
原理:返回函數(shù)調用,并把參數(shù)放在里面,讓前端的函數(shù)對它進行一個處理,用服務端代碼去響應JS代碼。
<!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>Document</title>
<style>
#result {
width: 300px;
height: 200px;
border: 1px solid #008c8c;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
// 處理函數(shù)
function handle (data) {
// 獲取元素
const result = document.querySelector('#result')
result.innerHTML = data.name
}
</script>
<!-- <script src="./app.js"></script> -->
<script src="http://127.0.0.1:8000/jsonp"></script>
</body>
</html>
原生JS代碼
const data = {
name:'張三'
}
handle(data)
express服務
// 1.引入express
const { response } = require('express')
const express = require('express')
// 2.創(chuàng)建應用對象
const app = express()
// 3.JSONP服務
app.all('/jsonp',(request,response)=>{
// response.send('console.log("hello jsonp");')
const data = {
name:'張三'
}
// 將數(shù)據(jù)轉換為字符串
let str = JSON.stringify(data)
// 返回結果 end()不會加特殊響應頭
// 返回的結果是一個函數(shù)調用,而函數(shù)的實參就是我們想給客戶端返回的結果數(shù)據(jù)
response.end(`handle(${str})`)
})
// 4.監(jiān)聽端口啟動服務
app.listen(8000,()=>{
console.log('服務已經(jīng)啟動,8080端口監(jiān)聽中....');
})
jsonp實踐:
<body>
用戶名:<input type="text" id="username">
<p></p>
<script>
// 獲取 input 元素
const input = document.querySelector('input')
const p = document.querySelector('p')
// 聲明 handle 函數(shù)
function handle (data) {
input.style.border = "solid 1px #f00"
// 修改 p 標簽的提示文本
p.innerHTML = data.msg
}
// 綁定事件
input.onblur = function () {
// 獲取用戶的輸入值
let username = this.value
// 向服務器發(fā)送請求,檢測用戶名是否存在
// 1.創(chuàng)建 script 標簽
const script = document.createElement('script')
// 2.設置標簽的 src 屬性
script.src = 'http://127.0.0.1:8000/username'
// 3.將script插入到文檔中
document.body.appendChild(script)
}
</script>
</body>
jQuery實現(xiàn)發(fā)送jsonp請求:
<!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>Document</title>
<style>
#result {
width: 300px;
height: 200px;
border: 1px solid #008c8c;
}
</style>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<button>點擊發(fā)送 jsonp 請求</button>
<div id="result">
</div>
<script>
$('button').eq(0).click(function(){
$.getJSON('http://127.0.0.1:8000/jquery?callback=?',function(data){
$('#result').html(`
名稱:${data.name},<br>
科目:${data.subject}
`)
})
})
</script>
</body>
</html>
// 1.引入express
const { response } = require('express')
const express = require('express')
// 2.創(chuàng)建應用對象
const app = express()
// 3.jQuery服務
app.all('/jquery',(request,response)=>{
// response.send('hello jQuery')
const data = {
name:'張三',
subject:['語文','數(shù)學','英語']
}
let str = JSON.stringify(data)
// 接收 callback 參數(shù)
let cb = request.query.callback
// 返回結果
response.end(`${cb}(${str})`)
})
// 4.監(jiān)聽端口啟動服務
app.listen(8000,()=>{
console.log('服務已經(jīng)啟動,8080端口監(jiān)聽中....');
})
CORS:跨域資源共享 。CORS是官方的跨域解決方案,它的特點是不需要在客戶端做任何特殊的操作,完全在服務器中進行處理,支持get和post請求,跨域資源共享標準新增了一組HTTP首部字段,允許服務器聲明哪些源站通過瀏覽器有權限訪問哪些資源。
CORS是通過設置一個響應頭來告訴瀏覽器,該請求允許跨域,瀏覽器收到該響應以后就會對響應放行。文章來源:http://www.zghlxwxcb.cn/news/detail-792784.html
<!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>Document</title>
</head>
<body>
<button>點擊發(fā)送請求</button>
<script>
const btn = document.querySelector('button')
btn.addEventListener('click',function(){
// 1.創(chuàng)建對象
const x = new XMLHttpRequest()
// 2.初始化設置
x.open('GET','http://127.0.0.1:8000/cors')
// 3.發(fā)送
x.send()
// 4.綁定事件
x.onreadystatechange = function(){
if(x.readyState ===4 ){
if(x.status >= 200 && x.status < 300){
// 輸出響應體
console.log(x.response );
}
}
}
})
</script>
</body>
</html>
// 1.引入express
const { response } = require('express')
const express = require('express')
// 2.創(chuàng)建應用對象
const app = express()
// 3.CORS
app.all('/cors',(request,response)=>{
// 設置響應頭
response.setHeader('Access-Control-Allow-Origin','*')
response.send('hello cors')
})
// 4.監(jiān)聽端口啟動服務
app.listen(8000,()=>{
console.log('服務已經(jīng)啟動,8080端口監(jiān)聽中....');
})
文章來源地址http://www.zghlxwxcb.cn/news/detail-792784.html
到了這里,關于Ajax--》請求操作以及跨域相關講解的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!