📜  xhr post send - Javascript (1)

📅  最后修改于: 2023-12-03 15:35:46.851000             🧑  作者: Mango

XHR POST send - Javascript

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:

  1. Create an XHR object using the XMLHttpRequest() constructor.
  2. Open the request using open() method with method type as "POST" and the URL to which the data will be sent.
  3. Set the request headers using the 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".
  4. Convert the data to be sent into a format suitable for the server using encodeURIComponent() method.
  5. Send the request using the send() method with the formatted data as argument.
  6. Listen for the response using the 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.