這篇文章主要介紹了如何通過promise解構封裝ajax請求,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
1.前端代碼
<!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>
/**
* 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
url: 'http://localhost:3000/details',
data: 'lid=0',
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()
}else{
xhr.send(data)
})
}
</script>
</body>
</html>
另:ajax實際代碼實作如下
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()
2.後端代碼
1) 建立一個後端項目
2) 在routes下建立index.js,users.js,代碼如下
// index.js
var express = require('express');
var router = express.Router( www.dlher.com );
/* 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;
// user.js
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: '使用者名或密碼錯誤'
3.注:
為避免跨域,可将前端代碼和後端同時放在一個項目内,使用同一位址,再發送請求調取接口