Home > Web Front-end > JS Tutorial > How to Send POST Data with XMLHttpRequest?

How to Send POST Data with XMLHttpRequest?

Patricia Arquette
Release: 2025-01-02 14:27:38
Original
384 people have browsed it

How to Send POST Data with XMLHttpRequest?

How to Submit POST Data using XMLHttpRequest

In scenarios where an application needs to submit data to the server, one can utilize XMLHttpRequest to send POST data.

In the provided HTML code, data is encapsulated within hidden form fields. To mirror this behavior using XMLHttpRequest in JavaScript, follow these steps:

  1. Create an XMLHttpRequest object:

    var http = new XMLHttpRequest();
    Copy after login
  2. Set the request method and URL:

    var url = 'get_data.php';
    http.open('POST', url, true);
    Copy after login
  3. Set the request headers:

    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    Copy after login
  4. Define the event listener for ready state changes:

    http.onreadystatechange = function() {//Call a function when the state changes.
     if(http.readyState == 4 && http.status == 200) {
         alert(http.responseText);
     }
    }
    Copy after login
  5. Send the data:

    http.send(params);
    Copy after login

For cases where the data is stored in an object, transform it into a URL-encoded format using the provided code snippet.

The above is the detailed content of How to Send POST Data with XMLHttpRequest?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template