Home >Web Front-end >JS Tutorial >How Can I Simulate an HTML Form POST Submission Using JavaScript?
In response to the query of how to emulate a POST request using a form submission in JavaScript, the optimal cross-browser approach is to create form elements dynamically and submit them.
To achieve this, follow these steps:
Create a Form Element:
const form = document.createElement('form'); form.method = 'post'; form.action = path;
Add Input Fields:
for (const key in params) { if (params.hasOwnProperty(key)) { const hiddenField = document.createElement('input'); hiddenField.type = 'hidden'; hiddenField.name = key; hiddenField.value = params[key]; form.appendChild(hiddenField); } }
Append Form and Submit:
document.body.appendChild(form); form.submit();
This technique dynamically creates a form, populates it with hidden input fields for the request parameters, and then initiates the submission process. Upon submission, the browser changes the location, simulating the behavior of a traditional form submit.
Example:
post('/contact/', {name: 'Johnny Bravo'});
The above is the detailed content of How Can I Simulate an HTML Form POST Submission Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!