Featured image of post Ajax - 基础小结(一)

Ajax - 基础小结(一)

Ajax 是浏览器提供的一套 API,可以通过JavaScript 调用,从而实现通过代码的方式控制请求与响应,进行网络编程。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// XMLHttpRequest——Ajax核心
// xhr就类似于浏览器(发送请求接收响应)
// 1.安装浏览器(用户代理)
var xhr = new XMLHttpRequest()
// 2.打开浏览器,输入网址
xhr.open('GET', 'http://www.abc.net/admanage.php?jsonpCallback=aa&action=getList')
// 3.回车,发送请求
xhr.send()
// 4.等待响应(响应需要时间,无法通过返回值的方式返回响应)
// 因为客户端永远不知道服务端何时才能返回我们需要的响应
// 所以 AJAX 采用事件的机制处理

// xhr.onreadystatechange = function(){} 下面的方法注册更优化
xhr.addEventListener('readystatechange', function(){
  // xhr状态改变的时候触发事件
  // console.log(this.readyState)
  // 2 3 4 如果需要捕获第一个状态 需要注意代码执行顺序
  if(xhr.readyState!==4) return 
  // 获取响应体
  console.log(this.responseText)
})

// 5。查看结果

readyState 状态变化

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
var xhr = new XMLHttpRequest()
console.log(xhr.readyState)
// 0 => 初始化请求代理对象 unsent
xhr.open('GET', './article.php')
console.log(xhr.readyState)
// 1 => open()已调用,建立起与服务端端口的连接 opened
xhr.send()
xhr.addEventListener('readystate', function(){
  console.log(this.readyState)
  // 2 => 已经接收到响应报文的响应头 headers_received
  // console.log(this.getAllResponseHeaders().split('\n'))
  // console.log(this.getAllResponseHeaders('server'))
  // 3=>正在下载loading, 4 =>可以拿到整个响应报文 done
})

onload 兼容

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var xhr = new XMLHttpRequest()
xhr.open('GET', '/a.php')
xhr.send(null)
xhr.onload = function(){
  console.log(this.readyState)
  // always 4 => 
  // xhr.onreadystatechange = function(){ if(readyState === 4){...} }
  console.log(this.responseText)
}
// onload 是 HTML5 新提供的API

遵循HTTP协议

1
2
3
4
5
6
var xhr = new XMLHttpRequest()
xhr.open('POST', '/add.php')
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') 
xhr.send('key1=value1&key2=value2')
// 请求头的 Content-Type 需要跟随请求体的内容格式变化
// xhr.send('{"foo":"123"}') => 'application/json'
Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy