📅  最后修改于: 2023-12-03 15:35:46.851000             🧑  作者: Mango
In Javascript, XHR (XMLHttpRequest) is an API used to send HTTP/HTTPS requests to a server and load the server response data back into the script. "POST" is one of the HTTP methods used to send data to the server.
To send a POST request using XHR, we need to perform the following steps:
XMLHttpRequest()
constructor.open()
method with method type as "POST" and the URL to which the data will be sent.setRequestHeader()
method. In case of a POST request, we need to set the Content-Type
header to "application/x-www-form-urlencoded"
or "multipart/form-data"
.encodeURIComponent()
method.send()
method with the formatted data as argument.onreadystatechange
event and handle the response data.Here is an example code snippet to send a POST request using XHR:
// create XHR object
var xhr = new XMLHttpRequest();
// prepare request
xhr.open('POST', 'http://example.com/submit', true);
// set headers (optional)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// prepare data
var data = {
name: 'John Doe',
age: 30
};
var formattedData = Object.keys(data).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key])).join('&');
// send request
xhr.send(formattedData);
// listen for response
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
Note that the server response data can be accessed using the responseText
property of the XHR object.
In conclusion, XHR POST send is an important functionality in Javascript to communicate with servers and send data. It is useful in creating dynamic web applications and integrating with APIs.