XMLHttpRequest 对象解析

来源:互联网 发布:中国流行音乐发展知乎 编辑:程序博客网 时间:2024/06/07 01:23

前言

ajax(Asynchronous JavaScript And XML),异步的JavaScript和XML,其核心就是XMLHttpRequest对象。
常用的jQuery中的$.ajax(), $.post(), $.get(), 就是基于XMLHttpRequest对象的一种ajax实现。
深入看下XMLHttpRequest对象还是挺有必要的呢。

XMLHttpReuest的属性(Properties)

readyState

有五种状态,老版本有所不同

0   UNSENT  open()还没有被调用1   OPENED  send()已经被调用(先open,后send2   HEADERS RECEIVED send()已经被调用,并且headers和状态已经可用)3   LOADING  下载中,responseText中已经有部分数据4   DONE    操作完成

status

HTTP的状态码,比如200表示请求成功。

statusText

返回一个包含完整的response字符串的DOMString,由服务器设置的,比如“200 OK”。

responseType

枚举类,指定返回的类型,可以是:json, text, document等等

response

根据responseType 不同,返回不同类型的数据,包含整个response的body。如果请求不完整或者不成功那么它是空的。

responseText

返回一个包含整个response的DOMString,对应的请求不成功或者还没有send,那么是null。

onreadystatechange

The XMLHttpRequest.onreadystatechange property contains the event handler to be called when the readystatechange event is fired, that is every time the readyState property of the XMLHttpRequest changes. The callback is called from the user interface thread.

每次readyState改变的时候都会调用onreadystatechange中指定的事件。

举个栗子:

var xmlhttp = new XMLHttpRequest(),    method = 'GET',    url = 'http://blog.csdn.net/';xmlhttp.open(method, url, true);xmlhttp.onreadystatechange = function () {    if (xmlhttp.readyState !== XMLHttpRequest.DONE) {        return;    }    if (xmlhttp.status !== 200) {        return;    }    console.log(xmlhttp.responseText);};xmlhttp.send();

timeout

The XMLHttpRequest.timeout property is an unsigned long representing the number of milliseconds a request can take before automatically being terminated. The default value is 0, which means there is no timeout. Timeout shouldn’t be used for synchronous XMLHttpRequests requests used in a document environment or it will throw an InvalidAccessError exception. When a timeout happens, a timeout event is fired.

timeout是一个无符号long,指定超时的毫秒数,当超过这个毫秒数的时候请求可以被自动终止,默认是0,也就是不会自动终止。当timeout发生的时候,timeout事件会被fire(ontimeout中指定的)。

XMLHttpReuest的事件(Events)

  1. onreadystatechange: The readystatechange event is fired when the readyState attribute of a document has changed.
  2. onloadstart: The loadstart event is fired when progress has begun.
  3. onprogress: The progress event is fired to indicate that an operation is in progress.
  4. onabort: The abort event is fired when the loading of a resource has been aborted.
  5. onerror: The error event is fired when a resource failed to load.
  6. onload: The load event is fired when a resource and its dependent resources have finished loading.
  7. ontimeout: 见上。
  8. onloadend: The loadend event is fired when progression has stopped (after “error”, “abort” or “load” have been dispatched).
0 0
原创粉丝点击