溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么利用promise及參數(shù)解構(gòu)封裝ajax請求

發(fā)布時間:2021-03-16 15:02:33 來源:億速云 閱讀:192 作者:小新 欄目:web開發(fā)

這篇文章主要介紹怎么利用promise及參數(shù)解構(gòu)封裝ajax請求,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!

1.前端代碼

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
</head>
<body>
 <script>
 /**
  * type: get/post
  * url: http://localhost:3000 http://localhost:3000/details http://localhost:3000/users
  * data: lid=5 / uname=lili&upwd=123456
  * dataType: '' / 'json', 如果服務(wù)端返回的是json格式字符串,就通過dataType通知ajax函數(shù)自動轉(zhuǎn)換為對象
  * **/
 ajax({
  type: 'get',
  url: 'http://localhost:3000',
  dataType: 'json'
 })
 // data 不寫在解構(gòu)時值默認(rèn)為 data: undefined
 ajax({
  type: 'get',
  url: 'http://localhost:3000/details',
  data: 'lid=0',
  dataType: 'json'
 })
 ajax({
  type: 'post', 
  url: 'http://localhost:3000/users', 
  data: 'uname=lili&upwd=123456',
 }).then(function(res){
  alert(res)
 })
 // dataType 不寫在解構(gòu)時值默認(rèn)為 dataType: undefined

 function ajax({type, url,data, dataType}){
  return new Promise(function(open){
  var xhr = new XMLHttpRequest()
  xhr.onreadystatechange = function(){
   if(xhr.readyState === 4 && xhr.status === 200){
   if(dataType === 'json'){
    var res = JSON.parse(xhr.responseText)
   }else{
    var res = xhr.responseText
   }
   console.log(res)
   open(res)
   }
  }

  if(type === 'get' && data !== undefined){
   url += `?${data}`
  }
  xhr.open(type, url, true)
  xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')

  if(type === 'get'){
   xhr.send()
  }else{
   xhr.send(data)
  }
  })
 }
 </script>
</body>
</html>

另:ajax實(shí)際代碼實(shí)現(xiàn)如下

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
</head>
<body>
 <script>
 var xhr = new XMLHttpRequest()
 xhr.onreadystatechange = function(){
  if(xhr.readyState === 4 && xhr.status === 200){
  console.log(xhr.responseText)
  }
 }
 xhr.open('get', 'http://localhost:3000', true)
 xhr.send()
 </script>
</body>
</html>

2.后端代碼

1) 創(chuàng)建一個后端項(xiàng)目

怎么利用promise及參數(shù)解構(gòu)封裝ajax請求

2) 在routes下創(chuàng)建index.js,users.js,代碼如下

// index.js
var express = require('express');
var router = express.Router();

/* GET home page. */
var products = [
 {
 lid:1,
 pname:'筆記本',
 price:3400
 },
 {
 lid:2,
 pname:'手機(jī)',
 price:5400
 },
 {
 lid:3,
 pname:'iPad',
 price:6400
 }
]

router.get('/', function(req, res, next) {
 res.send(products)
});

router.get('/details', function(req, res, next){
 var lid = req.query.lid
 res.send(products[lid])
})

module.exports = router;
// user.js
var express = require('express');
var router = express.Router();

/* GET users listing. */
router.post('/', function(req, res, next) {
 var uname = req.body.uname
 var upwd = req.body.upwd
 if(uname === 'lili' && upwd === '123456'){
 res.send('登陸成功')
 }else{
 res.send({
  code: 0,
  message: '用戶名或密碼錯誤'
 })
 }
});

module.exports = router;

3.注:

為避免跨域,可將前端代碼和后端同時放在一個項(xiàng)目內(nèi),使用同一地址,再發(fā)送請求調(diào)取接口

以上是“怎么利用promise及參數(shù)解構(gòu)封裝ajax請求”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI