操作promise及参数解构封装ajax请求的要领

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> /** * type: get/post * url: :3000 :3000/details :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() }else{ xhr.send(data) } }) } </script> </body> </html>

另:ajax实际代码实现如下

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta 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('https://www.jb51.net/', 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('https://www.jb51.net/', 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.注:

为制止跨域,可将前端代码和后端同时放在一个项目内,利用同一地点,再发送请求调取接口

到此这篇关于操作promise及参数解构封装ajax请求的文章就先容到这了,更多相关promise封装ajax请求内容请搜索剧本之家以前的文章或继承欣赏下面的相关文章但愿各人今后多多支持剧本之家!

您大概感乐趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsdfgz.html