利用promise及參數(shù)解構(gòu)封裝ajax請求的方法
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ù)自動(dòng)轉(zhuǎn)換為對象 * **/ ajax({ type: 'get', url: 'http://localhost:3000', datatype: 'json' }) // data 不寫在解構(gòu)時(shí)值默認(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)時(shí)值默認(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)建一個(gè)后端項(xiàng)目
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: '用戶名或密碼錯(cuò)誤' }) } }); module.exports = router;
3.注:
為避免跨域,可將前端代碼和后端同時(shí)放在一個(gè)項(xiàng)目內(nèi),使用同一地址,再發(fā)送請求調(diào)取接口
到此這篇關(guān)于利用promise及參數(shù)解構(gòu)封裝ajax請求的文章就介紹到這了,更多相關(guān)promise封裝ajax請求內(nèi)容請搜索碩編程以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持碩編程!