經過promise及參數解構封裝ajax請求的方法

本文主要介紹利用 promise和參數解構來封裝 ajax請求的方法,文章介紹的很詳細,應該對你們的學習和工做有必定的參考價值,有須要的朋友能夠參考html

1.前端代碼

<!DOCTYPE html>前端

<html>ajax

<head>express

 <meta charset="UTF-8">json

 <meta name="viewport" content="width=device-width, initial-scale=1.0">後端

 <title>Document</title>跨域

</head>promise

<body>app

 <script>ide

 /**

  * type: get/post

  * url: http://localhost:3000 http://localhost:3000/details http://localhost:3000/users

  * data: lid=5 / uname=lili&upwd=123456

  * dataType: '' / 'json', 若是服務端返回的是json格式字符串,就經過dataType通知ajax函數自動轉換爲對象

  * **/

 ajax({

  type: 'get',

  url: 'http://localhost:3000',

  dataType: 'json'

 })

 // data 不寫在解構時值默認爲 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 不寫在解構時值默認爲 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( www.babatianlong.com  )

  }else{

   xhr.send(data)

  }

  })

 }

 </script>

</body>

</html>


另:ajax實際代碼實現以下

<!DOCTYPE html>

<html>

<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) 建立一個後端項目

在這裏插入圖片描述

2) 在routes下建立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:'手機',

 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;

3.末:

爲了不跨域,能夠在一個項目中同時放置前端代碼和後端,使用相同的地址,再次發送 Request接口

這是一篇關於使用 promise和參數解構封裝 ajax請求的文章,更多相關可關注腳本之家!

相關文章
相關標籤/搜索