帮忙看看哪里出错
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="module">
import {ajax,get,getJSON,post} from './index.js'
const url ='https://www.imooc.com/api/http/search/suggest?words=js';
const xhr =ajax(url,{
method:'POST',
params:{username:'alex'},
data:{
age:18
},
responseType: 'json',
success(response){
console.log(response);
},
httpCodeError(err){
console.log('http code error',err);
},
error(xhr){
console.log('error',xhr);
},
abort(xhr){
console.log('abort',xhr);
},
timeout(xhr){
console.log('timeout',xhr);
}
})
</script>
</body>
</html>
*****index.js
import Ajax from "./ajax.js";
const ajax = (url,options) => {
return new Ajax(url,options).getXHR();
}
const get=(url,options)=>{
return ajax(url,{...options,method:"GET"});
}
const getJSON=(url,options)=>{
return ajax(url,{...options,method:"GET",responseType:'json'})
}
const post=(url,options)=>{
return ajax(url,{...options,method:"POST"});
}
export {ajax,get,getJSON,post};
********ajax.js
//常量
import {HTTP_GET,CONTENT_TYPE_JSON,CONTENT_TYPE_FORM_URLRNCODED} from './const.js'
//工具函数
import {serialize,addURLData,serializeJSON} from './utils.js';
//默认参数
import DEFAULTS from './defaults.js';
//class类
class Ajax {
constructor(url, options) {
this.url = url;
this.options =Object.assign({},DEFAULTS,options);
//初始化
this.init();
}
//初始化方法
init(){
const xhr = new XMLHttpRequest();
this.xhr = xhr;
//绑定响应事件处理程序
this.bindEvents()
//准备发送请求
xhr.open(this.options.method,this.url+this.addParam(),true);
//设置responseType
this.setResponseType();
//设置跨域是否携带cookie
this.setCookie();
//设置超时
this.setTimeout();
//发送请求
this.setData();
}
//绑定响应事件处理程序
bindEvents() {
const xhr =this.xhr;
//去除方法(解构出来)
const{success,httpCodeError,error,abort,timeout} = this.options;
//load
xhr.addEventListener('load', () => {
if(this.ok()){
success(xhr.response,xhr);
}else{
httpCodeError(xhr.response,xhr);
}
},false);
//error
//请求遇到错误时,触发error事件
xhr.addEventListener('error', () => {
error(xhr);
},false);
//abort
xhr.addEventListener('abort', () => {
abort(xhr);
},false);
//timeout
xhr.addEventListener('timeout', () => {
timeout(xhr);
},false);
}
//检查响应的HTTP状态码是否正常
ok(){
const xhr =this.xhr;
return (xhr.status>=200 && xhr.status<300)||xhr.status===304
};
//在地址上添加数据
addParam(){
const{params} = this.options;
//判断是不是null
if(!params) return '';
return addURLData(this.url,serialize(params));
}
//设置responseType
setResponseType(){
const xhr =this.xhr;
xhr.responseType =this.options.responseType;
}
//设置跨域是否携带cookie
setCookie(){
const xhr =this.xhr;
//判断是否携带Cookie,true就执行
if(this.options.withCredentials) {
xhr.withCredentials =true
}
}
//设置超时
setTimeout(){
const {timeoutTime} = this.options;
if(timeoutTime>0){
this.xhr.timeout =timeoutTime;
}
};
//发送请求
setData(){
const xhr =this.xhr;
//判断是传进来的是不是GET请求或者data:null
if(!this.isSendData()){
return xhr.send(null);
}
//声明一个变量来存放数据
let resultData = null;
const{data}= this.options;
//发送FormData格式的数据
if(this.isFormData()){
resultData =data;
}else if(this.isFormURLEncodedData()){
//发送application/x-www-form-urlencoded格式的数据
this.setContentType(CONTENT_TYPE_FORM_URLRNCODED);
resultData =serialize(data);
}else if(this.isJSONData()){
//发送application/json格式的数据
this.setContentType(CONTENT_TYPE_JSON);
resultData =serializeJSON (data);
}else{
//发送其他格式的数据
this.setContentType();
resultData =data;
}
xhr.send(resultData);
};
//是否需要使用send发送数据
isSendData(){
const {data,method}= this.options;
if(!data) return false;
if(method.toLOwerCase()===HTTP_GET.toLOwerCase()) return false;
return true;
}
//是否发送FormData格式的数据
isFormData(){
//判断data是不是FormData的实例
return this.options.data instanceof FormData;
}
//是否application/x-www-form-urlencoded格式的数据
isFormURLEncodedData(){
return this.options.contentType.toLOwerCase().includes(CONTENT_TYPE_FORM_URLRNCODED);
}
//是否application/json格式的数据
isJSONData(){
return this.options.contentType.toLOwerCase().includes(CONTENT_TYPE_JSON);
}
//设置Content-Type
setContentType(contentType=this.options.contentType){
if(!contentType) return;
this.xhr.setRequestHeader('Content-Yype',contentType)
}
//获取XHR对象
getXHR(){
return this.xhr;
}
}
export {Ajax};
*********utils.js
//工具函数
/* params:{
username:'alex',
age:18
}变成下面名值对
*/
//username=alex&age=18
const serialize = param =>{
const resules = [];
for(const[key,value] of Object.entries(param)){
resules.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
};
return resules.join('&');
}
//变成json格式
const serializeJSON = param =>{
return JSON.stringify(param);
}
//给URL添加参数
//www.imooc.com?words=js&
const addURLData =(url,data) =>{
//判断传进来的是不是null
if(!data) return '';
const mark =url.includes('?')?'&':'?';
return `${mark}${data}`;
}
export {serialize,addURLData,serializeJSON};
********defaults.js
//常量
import {HTTP_GET,CONTENT_TYPE_FORM_URLRNCODED} from './const.js'
//默认参数
export const DEFAULTS ={
method: HTTP_GET,
//请求头携带数据
params:null,
/* params:{
username:'alex',
age:18
}
*/
//如果有参数会以username=alex&age=18添加到url上
//请求体携带数据
data:null,
/* data:{
username:'alex',
age:18
}
*/
//data:FormData 数据
contentType:CONTENT_TYPE_FORM_URLRNCODED,
responseType: '',
//默认超时时间
timeoutTime: 0,
withCredentials: false,
//方法
success(){},
httpCodeError(){},
error(){},
abort(){},
timeout(){},
}
*********const.js
//常量
export const HTTP_GET = 'GET';
export const CONTENT_TYPE_FORM_URLRNCODED='application/x-www-form-urlencoded';
export const CONTENT_TYPE_JSON = 'application/json';
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星