Home >Web Front-end >JS Tutorial >How to Send POST Data with 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:
Create an XMLHttpRequest object:
var http = new XMLHttpRequest();
Set the request method and URL:
var url = 'get_data.php'; http.open('POST', url, true);
Set the request headers:
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
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); } }
Send the data:
http.send(params);
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!