preface
As a front-end development, it is an essential step to initiate a request to the server. Through the request, the server will return us the corresponding data, and we can make the corresponding operation according to the data. In general, many front-end developers now use third-party libraries to make requests, such as Axios, jQuery libraries, and so on.
Implement ajax requests using native JavaScript
The XMLHttpRequest object
The original use of a XMLHttpRequest object background and server data exchange, currently all browsers support XMLHttpRequest, specific code can refer to the following:
function initOption(options) { options.type = options.type.toUpperCase() || 'GET'; options.async = options.async || true; options.data = options.data || {}; options.dataType = options.dataType || 'JSON'; options.timeout = options.timeout || 10000; options.complete = options.complete || function(){}; options.success = options.success || function(){}; options.error = options.error || function(){}; return options } function formatParams(data) { if (typeof data === 'object') { const arr = []; for (var key in data) { arr.push(key + "=" + data[key]); } return arr.join("&"); } return data; } function ajaxXhr(url, options = {}) {// Initialize parameters, Add default value options = initOption(options) // Initialize the asynchronous object const XHR = new XMLHttpRequest(); Const data = formatParams(options.data); If (options.type === 'get ') {// Open the request, if (url.indexof ('? ')! == -1) { xhr.open(options.type, url + '&' + data); } else { xhr.open(options.type, url + '? ' + data); } xhr.send(); } if (options.type === 'POST') { xhr.open(options.type, url); Xhr. setRequestHeader(' content-type ', 'application/x-www-form-urlencoded'); // setRequestHeader xhr.setRequestHeader(' content-type ', 'application/x-www-form-urlencoded'); xhr.send(data); } xhr.onreadyStatechange = function() {// readyState five states // 0: Uninitialized. The open() method has not been called. // 1: Open. The open() method has been called; the send() method has not been called. // 2: Sent. The send() method has been called but no response has been received. // 3: Receiving Receiving. Partial responses have been received. // 4: Complete. All responses have been received and are ready to use. if (xhr.readyState === 4) { options.complete(); if (xhr.status === 200) { options.success(xhr.responseText); } else { options.error(xhr, xhr.status, xhr.statusText); }}}}Copy the code
The method of | describe |
---|---|
abort() | Stop the current request |
getAllResponseHeaders() | Return all response headers of the HTTP request as key/value pairs |
getResponseHeader(“header”) | Returns the string value of the specified header |
open(“method”,”URL”,[asyncFlag],[“userName”],[“password”]) | Establish calls to the server. The method parameter can be GET, POST, or PUT. The URL parameter can be a relative OR absolute URL. This method also includes three optional parameters, asynchronous or not, username, and password |
send(content) | Send a request to the server |
setRequestHeader(“header”, “value”) | Sets the specified header to the supplied value. You must call open() before setting any headers. Set the header and send it with the request (the ‘post’ method must be) |
fetch
The Fetch API provides a JavaScript interface for accessing and manipulating specific parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method, which provides a simple, reasonable way to asynchronously fetch resources across the network.
function initOption(options) { options.type = options.type.toUpperCase() || 'GET'; options.headers = options.headers || {}; options.data = options.data || {}; options.mode = options.mode || 'cors'; options.credentials = options.credentials || 'manual'; options.cache = options.cache || 'default'; return options } function formatParams(data) { if (typeof data === 'object') { const arr = []; for (var key in data) { arr.push(key + "=" + data[key]); } return arr.join("&"); } return data; } function ajaxFetch(url, options) {// Initialize parameters, Options = initOption(options) // Const data = formatParams(options.data); let fetchBody = null if (options.type === 'GET') { if (url.indexOf('? ')! == -1) { url = `${url}&${data}` } else { url = `${url}? ${data}` } } if (options.type === 'POST') { fetchBody = data } fetch(url, Object.assign({ body: fetchBody }, options)).then((res) => { console.log('res', res) }).catch((err) => { console.log('err', err) }) }Copy the code
Reference documentation
Advanced Programming in JavaScript (4th edition)
Using the Fetch ()