JavaScript study notes (XVI) XMLHttpRequest

1 Introduction

(1)AJAX(Asynchronous JavaScript and XML)

AJAX originally meant to get data from the server through XML documents asynchronous JavaScript, and then update the corresponding section of the page, to avoid refreshing the entire page

Later, the word slowly become synonymous communicate via a script in the browser and the server, it has more to expand on the original meaning

In other words, as long as the server sends a request to obtain the data through a script, the request will be referred to as AJAX request

(2)XMLHttpRequest

XMLHttpRequest Object Browser is built, we can send and receive a response to the request by the server object, data exchange

Many are achieved by the underlying AJAX XMLHttpRequest object

2, using

By the constructor XMLHttpRequest()to create an XMLHttpRequest object

XMLHttpRequest object common attributes as follows:

  • readyState: Read-only attribute indicates the current status of the request

    If it is 0, the request has been generated showing examples, but call the open()method

    If it is 1, it said it had invoked open()method, but did not call the send()method

    If it is 2, it said it had invoked send()method, and has received the header information returned by the server

    If it is 3, the data is being received body returned by the server

    If it is 4indicating that the server returns the data have been received, or an error occurs

  • response: Read-only attribute, the server returns the data indicates that the type of the responseTypedetermined value

  • responseType: Defines the type of data returned, the value is a string

    If it is 'text'or '', the server returns the text data represented

    If it is 'json', it indicates that the server returns Json objects

    If it is 'blob', it indicates that the server returns a Blob object

    If it is 'arraybuffer', it indicates that the server returns the object ArrayBuffer

    If it is 'document', it indicates that the server returns the Document object

  • responseText: Read-only attribute indicates the text data returned by the server if the request fails or null

  • responseXML: Read-only attribute of the Document object returned by the server, or null if the request fails

  • responseURL: Read-only attribute, indicating that the server returns data URL

  • status: Read-only attribute indicates the HTTP status code

  • statusText: Read-only attribute, HTTP state information indicates

  • timeout: Definition request timeout, if the time exceeds the request, the request is automatically ended

  • withCredentials: A Boolean value indicating whether the request when a cross-domain authorization information with

XMLHttpRequest object commonly used method is as follows:

  • open(): Initialization request, it receives the following five parameters

    Argument methodis a string representing the request method to be used

    Argument urlis a string representing a transmission request destination address

    Parameter asyncis a Boolean value that indicates whether the request requires asynchronous, the default is true

    Argument useris a string representing a user for authentication, the default is an empty string

    Parameter passwordis a string that represents passwords for authentication, the default is an empty string

  • setRequestHeader(): Setting request headers, you must be open()after the send()call before

  • overrideMimeType(): The server returns data parsed into the specified type, you must open()then send()call before

  • send(): Sending a request, the request can bring the body parameter

    Type of request may be a member null, String, Blob, ArrayBuffer, Document,FormData

  • abort(): Abort request

  • getAllResponseHeaders(): Get all response headers

  • getResponseHeader(): Gets the specified response header

XMLHttpRequest object popular events are as follows:

  • readystatechange: readyStateWhen triggered changes

  • loadstart: Fires when a request to start (HTTP request)

  • loadend: Trigger (request success or failure) When the request

  • load: Fires when the request is successful

  • error: Fires when the request errors

  • abort: Fires when the request is aborted

  • timeout: Triggered when the request timed out

  • progress: Listen to upload and download progress, the event corresponding event handler with an event object, that event object has three properties

    Attribute loadedindicates the amount of data have been transferred, the attribute totalindicates the total data amount

    Attribute lengthComputableindicates whether loading progress can be calculated, is a Boolean value

It should be noted, download trigger is xhran object of the progressevent, upload trigger is xhr.uploadan object of progressthe event

3, examples

(1) transmits a GET request

var xhr = new XMLHttpRequest()

xhr.responseType = 'text'

xhr.open('GET', 'http://www.httpbin.org/get')

xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            console.log(xhr.responseText)
        } else {
            console.error(xhr.statusText)
        }
    }
}

xhr.onerror = function() {
    console.log('error')
}

xhr.send()

(2) send a POST request

var xhr = new XMLHttpRequest()

xhr.open('POST', 'http://www.httpbin.org/post')

xhr.onload = function() {
    console.log(xhr.response)
}

xhr.onerror = function() {
    console.log('error')
}

var data = new FormData()
data.append('username', 'admin')
data.append('password', '12345')

xhr.send(data)

(3) receive pictures

var xhr = new XMLHttpRequest()

xhr.open('GET', '/path/to/image.png')

xhr.responseType = 'blob'

xhr.onload = function() {
    if (this.status === 200) {
    	var blob = xhr.response
        
        var img = document.createElement('img')
        img.onload = function() { window.URL.revokeObjectURL(img.src) }
        ime.src = window.URL.createObjectURL(blob)
        document.getElementById('container').appendChild(img)
    }
}

xhr.send()

(4) monitor progress

var xhr = new XMLHttpRequest()

xhr.open('GET', '/download/or/upload')

// 用于监听上传进度
xhr.onprogress = progressHandler
// 用于监听上传进度
xhr.upload.onprogress = progressHandler

function progressHandler(e) {
    if (e.lengthComputable) {
        console.log(e.loaded / e.total)
    } else {
        console.log('无法获取进度')
    }
}

xhr.send()

[Read More JavaScript series of articles, look at JavaScript study notes ]

Guess you like

Origin www.cnblogs.com/wsmrzx/p/12639248.html