When navigating to a different page requires a POST request, standard form submission methods may not be accessible via JavaScript. This article presents a solution to post data dynamically and change the browser's location, emulating form submission behavior.
To achieve this, create a form dynamically, populate it with hidden input fields containing the necessary parameters, and submit it:
<br>function post(path, params, method='post') {<br> const form = document.createElement('form');<br> form.method = method;<br> form.action = path;</p> <p>for (const key in params) {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">if (params.hasOwnProperty(key)) { const hiddenField = document.createElement('input'); hiddenField.type = 'hidden'; hiddenField.name = key; hiddenField.value = params[key]; form.appendChild(hiddenField); }
}
document.body.appendChild(form);
form.submit();
}
To submit data to '/contact/' with a parameter 'name' set to 'Johnny Bravo':
<br>post('/contact/', {name: 'Johnny Bravo'});<br>
In the provided solution, the 'hasOwnProperty' check ensures compatibility across browsers and prevents potential bugs.
The above is the detailed content of How Can I Simulate a POST Form Submission in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!