Mit Asynchronous JavaScript And XML kann man HTTP Requests machen. Meistens aber JSON statt XML

Deprecated

Requests sind der aktuellere heiße Scheiß

Request erstellen


const request = new XMLHttpRequest()

Fetch Data


request.open("get", <url>)
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
request.send([<DocumentBody>|<null>])

Return verarbeiten


request.onload = function (){
	let response = this.responseText
	let data = JSON.parse(this.responseText)
	//Code
}

Request Status


ValueStateDescription
0UNSENTClient has been created. open() not called yet.
1OPENEDopen() has been called. Server connection established
2HEADERS_RECEIVEDsend() has been called, and headers and status are available, request received
3LOADINGDownloading; responseText holds partial data. Processing Request
4DONERequest finished and response is ready
HTTP Status Codes
request.onreadystatechange = function() {
	let status = this.status //HTTP Status like 200, 400, 500
	let readState = this.readyState //AJAX Request Status
	let response = this.responseText //Data delivered
};

POST


const data = {
  fish: 'Salmon',
  weight: '1.5 KG',
  units: 5
};
const xhr = new XMLHttpRequest();
xhr.open('POST', '/inventory/add');
xhr.responseType = 'json';
xhr.send(JSON.stringify(data));
 
xhr.onload = () => {
  console.log(xhr.response);
};