POST Data Transmission Using XMLHttpRequest
In JavaScript, the XMLHttpRequest object provides a way to send data to a server asynchronously. This can be useful when transmitting form data without reloading the page.
Converting a Form Submission to XMLHttpRequest
Consider the following HTML form:
<form name="inputform" action="somewhere" method="post"> <input type="hidden" value="person" name="user"> <input type="hidden" value="password" name="pwd"> <input type="hidden" value="place" name="organization"> <input type="hidden" value="key" name="requiredkey"> </form>
To achieve the equivalent functionality using XMLHttpRequest, we can write the following code:
var http = new XMLHttpRequest(); var url = 'get_data.php'; var params = 'orem=ipsum&name=binny'; http.open('POST', url, true); http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); http.onreadystatechange = function() { if(http.readyState == 4 && http.status == 200) { alert(http.responseText); } } http.send(params);
This code opens a POST request to the specified URL, sets the necessary header information, and sends the parameters. You can modify the 'params' variable to include any data you need to transmit.
Object-to-Parameter Conversion
If you have an object you want to send as parameters, you can convert it to an array of URL-encoded key/value pairs using the following code:
var params = new Object(); params.myparam1 = myval1; params.myparam2 = myval2; let urlEncodedData = "", urlEncodedDataPairs = [], name; for( name in params ) { urlEncodedDataPairs.push(encodeURIComponent(name)+'='+encodeURIComponent(params[name])); }
This will create a string that can be used as the request parameters in the 'params' variable in the XMLHttpRequest call.
The above is the detailed content of How Can I Use XMLHttpRequest to Send POST Data in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!