# ajax > `XMLHttpRequest`(简称 `XHR`)的发明是为了解决早期 Web 开发中的一个关键问题:**如何在不刷新整个页面的情况下,与服务器进行异步通信** ## xhr ### get ```html Document
姓名:
年龄:
``` ### post ```js Document
姓名:
密码:
phone:
``` ## ajax ### 封装 ajax ```js let $ = { //option.type 请求类型 //option.url 请求地址 //option.data 请求体 //option.dataType 响应数据类型 //option.success 处理函数 /* 优化: 1. 传入的参数可以是键值对, 也可以是对象, 自动转成键值对 2. 响应的数据可以是json, 也可以是xml, 默认是对象 */ //封装一个把对象转成键值对的方法 getParams: function (data) { if (data) { //如果是对象, 转成键值对 if (typeof data == 'object') { let str = '' //遍历对象, 拼接 for (let key in data) { str += key + '=' + data[key] + '&' } //去掉最后多余的& return str.substr(0, str.length - 1) } else { //如果是字符串, 直接返回 return data } } else { //如果没有传递参数, 返回字符串 return '' } }, //es6新的语法糖 ajax(option) { let type = option.type || 'get' let url = option.url // console.log(this) let data = this.getParams(option.data) let dataType = option.dataType || 'text/html' let success = option.success //1. 初始化异步对象 let xhr = new XMLHttpRequest() //2.1 请求行 //当为get的时候, 请求行拼接url, 请求体为null if (type.toLowerCase() == 'get') { url += `?${data}` data = null } xhr.open(type, url) //2.2设置请求头 if (type.toLowerCase() == 'post') { xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') } //2.3设置请求体 xhr.send(data) //3.处理函数 xhr.onload = function () { //3.1 判断用户需要的格式, 接收事件请求响应并转化 let res = null if (dataType.toLowerCase() == 'json') { res = JSON.parse(this.response) } else if (dataType.toLowerCase() == 'xml') { res = this.responseXML } else { res = this.response } //3.2 调用函数 //逻辑短路, 没有传入函数直接跳过 success && success(res) } }, } ``` ### 使用 ```html Document
姓名:
密码:
phone:
``` ### formdata 文件上传 ```html Document

```