AI智能
改变未来

利用Promise对原生ajax进行封装-对jQuery的ajax进行封装


一、利用Promise对原生ajax进行封装

function ajax({method = \'get\',url = \"\",params = \"\"}) {const p = new Promise((resolve, reject) => {var xhr = new XMLHttpRequest();if (method == \"get\" && params != undefined) {url = url + \"?\" + params;}xhr.open(method, url, true);xhr.onreadystatechange = function() {if (this.status == 200 && this.readyState == 4) {resolve(this.responseText); //服务器给了正确的响应}};if (method == \"post\" && params != undefined) {xhr.send(params);} else {xhr.send();}});return p;}

二、对jQuery的ajax进行封装

//用对jQuery的ajax进行封装function http({url = \'\', //请求地址type = \'get\', //请求方式,默认getdata = {} //请求传递的数据}) {const p = new Promise((resolve, reject) => {$.ajax({url,type,data,dataType: \'json\',success: function(res) {resolve(res[\'list\']);},error: function(err) {reject(err);}});});return p;}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » 利用Promise对原生ajax进行封装-对jQuery的ajax进行封装