JavaScript开发者手册

[ AJAX ] 快速参考

2018-07-06  本文已影响0人  爱上落入尘世间的你

参考阮一峰老师的教程

一般用法

xhr= new XMLHttpRequest()
xhr.open('GET', 'https://www.twesix.cn', true)

// 直接监听onload即可,不必设置函数检查readyState
xhr.onload = function()
{
    // success
    console.log(xhr.response)
}
xhr.onerror = function()
{
    // error
}
xhr.onloadend = function()
{
    // success or error
}

ajax对象的readyState

ajax对象的属性

xhr.response
// 服务器返回的数据体(即 HTTP 回应的 body 部分)
// 它可能是任何数据类型,比如字符串、对象、二进制对象等等
// 具体的类型由XMLHttpRequest.responseType属性决定
//该属性只读。

xhr.responseType
xhr.responseText
xhr.responseXML
xhr.responseURL

xhr.status // 状态码
xhr.statusText // 状态码对应的字符串
// 200, OK,访问正常
// 301, Moved Permanently,永久移动
// 302, Moved temporarily,暂时移动
// 304, Not Modified,未修改
// 307, Temporary Redirect,暂时重定向
// 401, Unauthorized,未授权
// 403, Forbidden,禁止访问
// 404, Not Found,未发现指定网址
// 500, Internal Server Error,服务器发生错误

xhr.timeout
XMLHttpRequest.withCredentials // 是否启用cookie

xhr.upload // 上传进度

ajax对象的方法

xhr.open('METHOD', url, async)
xhr.setRequestHeader
xhr.overrideMimeType
xhr.send(any object)
xhr.getResponseHeader
xhr.getAllResponseHeaders
xhr.abort
xhr.onloadstart = fn
xhr.onprogress = fn(event)
 { 
    console.log(event.loaded, event.total, event.lengthComputable)
}
xhr.onabort = fn
xhr.onerror = fn
xhr.onload = fn
xhr.onloadend = fn
xhr.onreadystatechange = fn // 监听readyState的改变
xhr.ontimeout = fn

navigator.sendBeacon

function analytics(state) {
  if (!navigator.sendBeacon) return;

  var URL = 'http://example.com/analytics';
  var data = 'state=' + state + '&location=' + window.location;
  navigator.sendBeacon(URL, data);
}
上一篇 下一篇

猜你喜欢

热点阅读