) {
console.log(this.response);
3. 使用XMLHttpRequest
发送post
请求(有请求体)
由于post请求要带请求体,请求体有三种格式,为了方便服务器接收数据,当提交请求时,需要指定一个叫做Content-Type的请求头
请求体格式:
参数=值&参数=值
代码示例:
const data = {
name: 'xxx',
age: xx,
let xhr = new XMLHttpRequest()
xhr.open('POST', 'http://XXXX')
const usp = new URLSearchParams(data)
const query = usp.toString()
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
xhr.send(query)
xhr.addEventListener('load', function () {
console.log(this.response)
以json
格式传参
代码示例:
const data = {
name: 'xxx',
age: xx,
let xhr = new XMLHttpRequest()
xhr.open('POST', 'http://XXXX')
const str = JSON.stringify(data)
xhr.setRequestHeader('Content-type', 'application/json')
xhr.send(str)
xhr.addEventListener('load', function () {
console.log(this.response)
new ForData()
格式
const data = {
name: 'xxx',
age: xx,
let xhr = new XMLHttpRequest()
xhr.open('POST', 'http://XXXX')
const formdata = new FormData(data)
xhr.setRequestHeader('Content-type', 'application/form-data')
xhr.send(formdata)
xhr.addEventListener('load', function () {
console.log(this.response)
利用XMLHttpRequest
来封装自己的ajax
function ajax ({ url, type, data = '', success }) {
const xhr = new XMLHttpRequest()
if (type === 'get') {
if (typeof data === "object") {
data = (new URLSearchParams(data)).toString()
xhr.open(type, url + '?' + data)
xhr.send()
} else if (type === 'post') {
xhr.open(type, url)
if (typeof data === "string") {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
xhr.send(data)
} else if (typeof data === "object") {
if (data instanceof FormData) {
xhr.send(data)
} else {
xhr.setRequestHeader('Content-type', 'application/json')
const str = JSON.stringify(data);
console.log(typeof str)
xhr.send(str)
xhr.addEventListener('load', function () {
const obj = JSON.parse(this.response)
success(obj)
复制代码