To submit POST requests in JavaScript and navigate to a different page as if submitting a form, consider this solution:
/** * sends a request to the specified url from a form. this will change the window location. * @param {string} path the path to send the post request to * @param {object} params the parameters to add to the url * @param {string} [method=post] the method to use on the form */ function post(path, params, method='post') { // Create a form and add it to the DOM const form = document.createElement('form'); form.method = method; form.action = path; document.body.appendChild(form); // Create hidden input fields for each parameter 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); } } // Submit the form form.submit(); // Optionally, remove the form from the DOM document.body.removeChild(form); } // Example: post('/contact/', {name: 'Johnny Bravo'}); ````
The above is the detailed content of How Can I Submit POST Requests in JavaScript Using a Form?. For more information, please follow other related articles on the PHP Chinese website!