To transmit data via an XMLHttpRequest in JavaScript, it's essential to understand the process. 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 replicate this form's behavior using an XMLHttpRequest in JavaScript, follow these steps:
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);
Alternatively, if you have an object containing the data you want to send, convert it to parameters 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])); }
The above is the detailed content of How Can I Send POST Data Using XMLHttpRequest in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!