JavaScript学习笔记(四)Ajax

1. XMLHttpRequest使用

const xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    if ((xhr.status >=200 && xhr.status < 300) || xhr.status === 304) {
      console.log(xhr.status, xhr.statusText, xhr.responseText, xhr.responseXML)
    }
  }
}
xhr.open('get', 'example.html', false)
xhr.send(null)
xhr.abort()
xhr.setRequestHeader('key', 'value')
xhr.getResponseHeader('key')
xhr.getAllResponseHeaders()

2. get

function addURLParam(url, name, value) {
  url += (url.indexof('?') === -1 ? '?' : '&')
  url += encodeURIComponent(name) + '=' + encodeURIComponent(value)
  return url
}

3. post form

// formData
const data = new FormData()
data.append('name', 'waite')
xhr.send(data)

const form = document.getElementById('user-info')
xhr.send(new FormData(form))

4. 超时

xhr.timeout = 1000
xhr.ontimeout = function() {
  console.log('timeout')
}

5. 重写响应的mime类型(必需在send方法之前)

xhr.overrideMimeType('text/html')

6. 进度事件

xhr.onloadstart = function() {}
xhr.onprogress = function(event) {
  event.target === xhr
  event.lengthComputable
  event.position //已接收
  event.totalSize // Content-Length 预期字节
}
xhr.onerror = function() {}
xhr.onabort = function() {}
xhr.onload = function(event) {
  event.target === xhr
}
xhr.onloadend = function() {}

7. 跨域

// 跨域
// 请求头加origin
origin: http:// www.nc.net
// 服务器接受请求时,响应
Access-Control-Allow-Origin: http://www.nc.net

// XMLHttpRequest跨域
传入绝对URL
限制:
1. 不能使用setRequestHeader()设置头部
2. 不能发送和接收cookie
3. getAllResponseHeaders()返回空字符串
对于本地资源,用相对URL,对远程资源,用绝对URL

xhr.withCredentials

 

7.1 图像Ping

var img = new Image()
img.onload = img.onerror = function() {
  console.log('done)
}
img.src = "http://www.example.com/test?name=waite"
// 1. 只能GET
// 2. 无法访问服务器的响应文本

7.2 JSONP

客户端把callback函数和参数传给服务器,服务器拼接成js代码返回客户端。

const handleFunc = function(data) {
  console.log(data)   
}
url = 'http://www.example.com/query.js?callback=handleFunc&code=aaa'
const script = document.createElement('script')
script.src = url
document.getElementsByTageName('head')[0].appendChild(script)

7.3 comet

1. 短轮询
浏览器向服务器定时发送请求,看有没有更新
2. 长轮询
浏览器发送请求后,服务器保持打开,直到有数据可发送

7.4 Web Socket

// 创建后马上尝试连接
consr ws = new WebSocket('ws://www.example.com')
ws.readyState // 0 正在建立 1 已经建立 2 正在关闭  3 已经关闭
ws.close()
// 只能发送文本
ws.send('Heoll World!')
ws.send(JSON.stringify(obj))

ws.onmessage = function(event) {
  const data = event.data      
}

ws.onopen = function(){}
ws.onerror = function(){}
ws.onclose = function(event){
  event.wasClean
  event.code
  event.reason
}

 

posted @ 2019-04-23 21:37  zhoulixue  阅读(178)  评论(0编辑  收藏  举报