介绍
本篇文章给大家分享的是有关使用承诺怎么对ajax请求进行封装,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
1。前端代码
& lt; ! DOCTYPE html> & lt; html  lang=癳n"祝辞 & lt; head> ,& lt; meta charset=癠TF-8"比; ,& lt; meta name=皏iewport",内容=翱矶?设备宽度,初始=1.0,比; ,& lt; title> Document & lt;/head> & lt; body> ,& lt; script>/* * *,才能类型:get/post *,才能url:, http://localhost: 3000, http://localhost: 3000/details http://localhost: 3000/用户 *,才能数据:,盖子=5,/,uname=lili& upwd=123456 *,才能数据类型:,& # 39;& # 39;,/,& # 39;json # 39;,,如果服务端返回的是json格式字符串,就通过数据类型通知ajax函数自动转换为对象 ,*,* */,ajax ({ 类型:才能,& # 39;得到# 39; ,,url: & # 39; http://localhost: 3000 & # 39; 数据类型:才能,& # 39;json # 39; ,}) ,//data 不写在解构时值默认为,数据:未定义 ,ajax ({ 类型:才能,& # 39;得到# 39; ,,url: & # 39; http://localhost: 3000/细节# 39; ,,数据:& # 39;盖子=0 & # 39; 数据类型:才能,& # 39;json # 39; ,}) ,ajax ({ 类型:才能,& # 39;文章# 39;,, ,,url: & # 39; http://localhost: 3000/用户# 39;,, ,,数据:& # 39;uname=lili& upwd=123456 & # 39; ,})(函数(res) { 警报(res)才能 ,}) ,//dataType 不写在解构时值默认为,数据类型:未定义 ,function ajax({类型,url,数据,数据类型}){ return 才能;new 承诺(函数(打开){ var 才能;xhr =, new XMLHttpRequest () xhr.onreadystatechange 才能=,函数(){ ,,如果(xhr.readyState ===, 4,,,, xhr.status ===, 200) { ,,如果(dataType ===, & # 39; json # 39;) { ,,,var res =, JSON.parse (xhr.responseText) 其他,,}{ ,,,var res =xhr.responseText ,,} ,,console.log (res) ,才能打开(res) ,,} ,,} 如果才能(type ===, & # 39;得到,,,,,data !==,未定义){ ,,url +=,”? ${数据}' ,,} xhr.open才能(url类型,,,,真的) xhr.setRequestHeader才能(& # 39;内容类型# 39;,& # 39;应用程序/x-www-form-urlencoded& # 39;) 如果才能(type ===, & # 39;得到# 39;){ ,,xhr.send () }{其他才能 ,,xhr.send(数据) ,,} })才能 ,} ,& lt;/script> & lt;/body> & lt;/html>
另:ajax实际代码实现如下
& lt; ! DOCTYPE html> & lt; html  lang=癳n"祝辞 & lt; head> ,& lt; meta charset=癠TF-8"比; ,& lt; meta name=皏iewport",内容=翱矶?设备宽度,初始=1.0,比; ,& lt; title> Document & lt;/head> & lt; body> ,& lt; script> ,var xhr =, new XMLHttpRequest ()=,xhr.onreadystatechange 函数(){ 如果才能(xhr.readyState ===, 4,,,, xhr.status ===, 200) { console.log才能(xhr.responseText) ,,} ,} ,xhr.open(& # 39;得到# 39;,,& # 39;http://localhost: 3000 & # 39;,,真的) ,xhr.send () ,& lt;/script> & lt;/body> & lt;/html>
2。后端代码
1)创建一个后端项目
2)在路线下创建index.js,用户。js,代码如下
//, index.js var express =,要求(& # 39;表达# 39;); var router =, express.Router ();/*,GET home 页面只*/var products =, ( ,{ ,盖:1、 ,pname: & # 39;笔记本& # 39;, 价格:3400 }, ,{ ,盖:2 ,pname: & # 39;手机& # 39;, 价格:5400 }, ,{ ,盖:3, ,pname: & # 39; ipad # 39; 价格:6400 ,} ] router.get(& # 39;/& # 39;,,功能(要求的事情,,,,下一个),{ ,res.send(产品) }); router.get(& # 39;/细节# 39;,,功能(要求的事情,,,,下一个){ ,var lid =req.query.lid (盖子),res.send(产品) })=module.exports 路由器;
//, user.js var express =,要求(& # 39;表达# 39;); var router =, express.Router ();/*,GET users 清单只*/router.post(& # 39;/& # 39;,,功能(要求的事情,,,,下一个),{ ,var uname =req.body.uname ,var upwd =req.body.upwd ,如果(uname ===, & # 39;丽丽# 39;,,,,upwd ===, & # 39; 123456 & # 39;) { ,res.send(& # 39;登陆成功& # 39;) ,其他}{ ,res.send ({ ,,代码:0, null null null null null null使用承诺怎么对ajax请求进行封装