Request method of Ajax encapsulation based on promise

Keywords: Javascript Ajax http

1.Ajax requests obtain more information from the server asynchronously, which means that users can update the latest data of the server without refreshing the web page as long as they trigger an event.
2. Using Ajax, you must call the open() method, which accepts three parameters: the type of request to send (get, post), the URL of the request, and whether it is asynchronous

//Specify the request type (POST or GET), request address url, asynchronous async (true) and synchronous (false)
xhr.open(obj.type, obj.url + "?" + params, obj.async)

3. The open() method does not actually send a request, but just starts a request for sending. Send the request through the send() method, which accepts a parameter as the data sent by the request body. If it is not required, null must be filled in. After executing the send() method, the request is sent to the server

//Send request
xhr.send(null)

4. After receiving the response, the data of the response will automatically fill in the XMLHttpRequest object (XHR) object. The relevant attributes are as follows:

Attribute nameexplain
responseTextThe text returned as the response body
responseXMLIf the content type of the response body is "text/xml" or "application/xml", the XML DOM document containing the response data is returned
responseTextThe text returned as the response body
statusHTTP status of the response
statusTextDescription of HTTP status

5. After accepting the response, the first step is to check the status attribute to ensure that the response has been returned successfully. Generally, the HTTP status code is 200 as a sign of success

200 – OK – the server successfully returned to the page
400 – Bad Request – syntax error causes server not to recognize
401 – Unauthorized – request requires user authentication
404 – Not found – the specified URL cannot be found on the server
500 – Internal Server Error -- the server encountered an unexpected error and was unable to complete the request
503 – ServiceUnavailable – the request cannot be completed due to server overload or maintenance

6. When using asynchronous calls, you need to trigger the readystatechange event, and then detect the readyState attribute. This attribute has five values:
0 - uninitialized, open() method has not been called;
1 - start, call the open() method, not the send() method; The server connection has been established;
2 - send, the send() method has been called, and no response has been received; Request received;
3 - receive, partial response data has been received; Request processing;
4 - completed, all response data have been received; The request has been completed;
code:

function ajax(obj) {
		var  promise = new Promise((resolve,reject)=>{
			var xhr = null;
			var params = formsParams(obj.data)
			if (window.XMLHttpRequest) {
			    xhr = new XMLHttpRequest();
			} else {
			    xhr = new ActiveXObject("Microsoft.XMLHTTP");//Compatible with IE6 and below browsers
			}
			//Connect and send
			if (obj.type === 'GET') {
			    xhr.open(obj.type, obj.url + "?" + params, obj.async)
				//GET request is the most common type of request and is most commonly used to query the server for some information. If necessary, you can append the query string parameter to the end of the URL for submission to the server.
			    xhr.send(null)
			} else if (obj.type === 'POST') {
				//Set the content type when the form is submitted
			    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			    xhr.open(obj.type, obj.url + "?" + params, obj.async)
				//POST requests can contain a lot of data. Many of us use POST transmission when submitting forms.
			    xhr.send(params)
			}
			xhr.onreadystatechange = function() {
			    if (xhr.readyState === 4) {
			        if (xhr.status >= 200 && xhr.status < 300) {
						resolve(xhr.responseText);
			        }else{
						reject(xhr.staus);
					}
			    }
			}
		})
		return promise
	}
	//Parameter formatting
	function formsParams(data) {
	    var arr = []
	    for (let index in data) {
	        arr.push(data[index])
	    }
	    arr.join('&')
	}
	
	//call
	ajax({
	    type: 'GET',
	    url: 'https://api.apiopen.top/getJoke',
	    data: {},
	    async: true
	}).then(res=>{
		document.write(res);
	}).catch(err=>{
		console.log('Request failed!');
	})

Posted by Devil_Banner on Wed, 13 Oct 2021 05:35:06 -0700