6-1FormData|6-2~6封装Ajax|6-7使用Promise改造封装好的Ajax
FormData
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<form id="login" action="https://www.imooc.com/api/http/search/suggest?words=js" method="post"
enctype="application/x-www-form-urlencoded">
<input type="text" name="username" placeholder="用户名" />
<input type="password" name="password" placeholder="密码" />
<input id="submit" type="submit" value="提交" />
</form>
</head>
<body>
<script>
//1.使用Ajax提交表单
//2.FormDate的基本用法
//通过HTML表单元素创建FormDate对象
//const fd = new FormData(表单元素);
//data.append('age',18);
//data.append('sex','male');
//xhr.send(fd);
//通过append()方法添加数据
const login = document.getElementById('login');
//console.log(login.username);
//console.log(login.password);
const {
username,
password
} = login;
const btn = document.getElementById('submit');
const url = 'https://www.imooc.com/api/http/search/suggest?words=js'
btn.addEventListener(
'click',
e => {
//阻止表单自动提交
e.preventDefault();
//表单数据验证
//发生Ajax请求
const url = 'https://www.imooc.com/api/http/search/suggest?words=js';
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', () => {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
console.log(xhr.response);
}
},
false
);
xhr.open('POST', url, true);
//组装数据
//const data = 'username=${username.value}&password=${passwrod.value}';
const data = new FormData(login);
data.append('age',18);
data.append('sex','male');
//console.log(data);
/* for(const item of data){
console.log(item);
} */
// xhr.setRequestHeader(
// 'Content-Type',
// 'application/x-www-form-urlencoded'
// );
xhr.send(data);
//xhr.send('username=lyw&passwrod=12345')
},
false
);
</script>
</body>
</html>
封装Ajax1
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="module">
/* const url = 'https://www.imooc.com/api/http/search/suggest?words=js';
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', () => {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
console.log(xhr.response);
}
}, false);
xhr.open('GET', url, true);
xhr.send(null); */
//import{set,get,remove} from './js/cookie';
import {ajax,get,getJSON,post} from './js/index';
const url = 'https://www.imooc.com/api/http/search/suggest?words=js';
const xhr = ajax(url, {
module: 'POST',
params: {
username: 'lyw'
},
data: {
age: 18
},
responseType: 'json',
success(response) {
console.log(response);
},
httpCodeErro(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>
defaulst.js
//常量
import { HTTP_GET,CONTENT_TYPE_FROM_URLENCODED} from "./constants.js";
//默认参数
const DEFAULTS = {
method: 'HTTP_GET',
//请求头携带的数据
params: null,
/* params:{
username:'lyw',
age:18
} */
//username=alex&age=18
//请求体携带的数据
data: null,
/* data:{
username:'lyw',
age:18
},
data.FormData 数据 */
contentType: CONTENT_TYPE_FROM_URLENCODED,
responseType: '',
timeoutTime: 0,
withCredentials: false,
//方法
success() {},
httpCodeError() {},
error() {},
abort() {},
timeout() {}
};
export default DEFAULTS
index.js
import Ajax from './Ajax1';
//常量
import {
ERROR_HTTP_CODE,
ERROR_REQUEST,
ERROR_TIMEOUT,
ERROR_AB0RT,
ERROR_HTTP_CODE_TEXT,
ERROR_REQUEST_TEXT,
ERROR_TIMEOUT_TEXT,
ERROR_AB0RT_TEXT
} from './constants'
const ajax1 = (url,option)=>{
//return new Ajax (url,options).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_CODE_TEXT} ${status}`
});
},
error() {
reject({
type: ERROR_REQUEST,
text: ERROR_REQUEST_TEXT
});
},
abort() {
reject({
type: ERROR_TIMEOUT,
text: ERROR_TIMEOUT_TEXT
});
},
timeout() {
reject({
type: ERROR_AB0RT,
text: ERROR_AB0RT_TEXT
});
},
}
}).getXHR();
});
p.xhr=xhr;
p.ERROR_HTTP_CODE=ERROR_HTTP_CODE_TEXT;
p.ERROR_REQUEST=ERROR_REQUEST_TEXT;
p.ERROR_TIMEOUT=ERROR_TIMEOUT_TEXT;
p.ERROR_AB0RT=ERROR_AB0RT_TEXT;
};
const ajax = (url,option) => {
return new Ajax(url,option).getXHR();
};
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};
Ajax.js
//工具函数
import {serialize,addURLData,serializeJSON} from 'utils.js';
import DEFAULTS from 'defaults.js';
//常量
import {
HTTP_GET,
CONTENT_TYPE_FROM_URLENCODED,
CONTENT_TYPE_JSON
} from 'constants.js';
//Ajax类
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.bingEvents();
xhr.open(this.options.method, this.url + this.addParam(), true);
//设置 responseType
this.setResponseType();
//设置跨域是否携带 Cookie
this.setCookie;
//设置超时
this.setTimeout();
//发送请求
this.sendData();
}
//www.imooc.com?
//绑定响应时间处理程序
bingEvents() {
const xhr = this.xhr;
const {
success,
httpCodeError,
error,
abort,
timeout
} = this.xhr;
xhr.addEventListener('load', () => {
if (this.ok) {
success(xhr.response, xhr);
} else {
httpCodeError(xhr.status, 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 {
param
} = this.options;
if (!param) return '';
return addURLData(this.url, serialize(param));
}
//设置 responseType
setResponseType() {
xhr.responseType = this.options.responseType;
}
//设置跨域是否携带Cookie
setCookie() {
if (this.options.withCredentials) {
this.xhr.withCredentials = true;
}
}
//设置超时
setTimeout() {
const {
timeoutTime
} = this.options;
if (timeoutTime > 0) {
this.xhr.timeout = timeoutTime;
}
}
//发送请求
sendData() {
const xhr = this.xhr;
if (!this.isSendData) {
return xhr.send(null);
}
let resultData = null;