使用Promise改造封装好的AJAX
修改index.js
import Ajax from 'ajax.js'; import { ERROR_ABOUT } from './封装AJAX4'; import { ERROR_TIMEOUT } from './封装AJAX4'; import { ERROR_REQUESTE } from './封装AJAX4'; import { ERROR_HTTP_CODE } from './封装AJAX4'; const ajax = (url,option) => { //return new Ajax(url,option).getXHR(); let xhr; const p = new Promise((resolve,reject) => { xhr = new Ajax(url,{ ...option, ...{ success(response){ resolve(response); }, httpCodeError(status){ reject({ type: ERROR_HTTP_CODE, text:'${ERROR_HTTP_HTTP_CODE_TEXT}:{status}' }); }, error(){ reject({ type: ERROR_REQUESTE, text:ERROR_REQUESTE_TEXT }); }, abort(){ reject({ type: ERROR_ABOUT, text:ERROR_ABOUT_TEXT }); }, timeout(){ reject({ type: ERROR_TIMEOUT, text:ERROR_TIMEOUT_TEXT }); }, } }).getXHR(); }); p.xhr=xhr; p.ERROR_HTTP_CODE=ERROR_HTTP_CODE; p.ERROR_REQUESTE=ERROR_REQUESTE; p.ERROR_TIMEOUT=ERROR_TIMEOUT; p.ERROR_ABOUT=ERROR_ABOUT; return p; }; const get = (url,option) => { return new ajax(url,{...option,method:'GET'}); }; const getJSON = (url,option) => { return new ajax(url,{...option,method:'GET',responseType:'json'}); }; const POST = (url,option) => { return new ajax(url,{...option,method:'POST'}); }; export {ajax,get,getJSON,POST};
修改defaults.js
export const HTTP_GET = 'GET'; export const CONTENT_TYPE_FROM_URLENCODED='application/x-www-form-urlencoded'; export const CONTENT_TYPE_JSON='application/json'; export const ERROR_HTTP_CODE=1; export const ERROR_HTTP_CODE_TEXT='HTTP状态码异常'; export const ERROR_REQUESTE=2; export const ERROR_REQUEST_TEXT='请求被阻止'; export const ERROR_TIMEOUT=3; export const ERROR_TIMEOUT_TEXT='请求超时'; export const ERROR_ABOUT=2; export const ERROR_ABOUT_TEXT='请求终止';
新建html
使用Promise改造封装好的AJAX.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>使用Promise改造封装好的AJAX</title> </head> <body> <script type="module"> import {ajax,get,getJSON,post} from '../封装AJAX3'; const url = 'https://www.imooc.com/api/http/search/suggest?wirds=js'; const p = getJSON(url,{ params:{username:'alex'}, data:{age:18}, }); const{ ERROR_HTTP_CODE,ERROR_REQUESTE,ERROR_TIMEOUT,ERROR_ABOUT}=p; p.then(Response=>{ console.log(Response); }).catch(err=>{ //console.log(err); switch(err.type){ case ERROR_HTTP_CODE: console.log(err.text); break; case ERROR_REQUESTE: console.log(err.text); break; case ERROR_TIMEOUT: console.log(err.text); break; case ERROR_ABOUT: console.log(err.text); break; } }); </script> </body> </html>
标签:HTTP,const,url,ABOUT,AJAX,Promise,ERROR,封装,export From: https://www.cnblogs.com/yu3304/p/17272467.html