ajax基础语法
1.创建一个ajax对象
var xhr = new XMLHttpRequest()
2.配置本次的请求信息
xhr.open(请求方式, 请求地址, 是否异步)
请求方式:按照接口文档书写 get/post、 请求地址: 按照接口文档书写、 是否异步: true,false
3.注册请求完成事件
xhr.onload = funciton () {}
4.把本次请求发送出去
xhr.send()
var xhr = new XMLHttpRequest()
xhr.open('GET', 'http://localhost:8888/test/first' , false)
//请求完成:本次请求发出去,服务器收到请求,并且返回的信息返回到浏览器
xhr.onload = funciton () {
//语法:xhr.responseText //后端返回的信息
console.log('请求完成')
}
xhr.send()
ajax数据处理
var xhr = new XMLHttpRequest()
xhr.open('GET', 'http://localhost:8888/test/first' , false)
xhr.onload = funciton () {
//xhr.responseText json格式数据
//语法:JSON.parse(json格式数据) 解析成对象
var res = JSON.parse(xhr.responseText)
}
xhr.send()
请求方式区别
get
- 偏向获取的语义化
- 参数是查询字符串
- 大小限制8KB左右
- 参数位置在地址后面
xhr.open('GET', 'xxx?key=value&key2=value2' , false)
var xhr = new XMLHttpRequest()
xhr.open('GET', 'http://localhost:8888/test/first?name=姓名&age=18' , false)
xhr.onload = funciton () {
var res = JSON.parse(xhr.responseText)
}
xhr.send()
post
- 偏向提交的语义化、
- 参数多样化,需要特殊说明
- 语法:xhr.setRequestHeader('contnet-type', 传递参数的格式)
- 理论上没有限制
- 参数位置在请求体内
xhr.send(key=value&key2=value2)
var xhr = new XMLHttpRequest()
xhr.open('POST', 'http://localhost:8888/test/first' , false)
xhr.onload = funciton () {
var res = JSON.parse(xhr.responseText)
}
//特殊说明
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
xhr.send('name=姓名&age=18')