要在 JavaScript 中提交 POST 请求并像提交表单一样导航到不同的页面,请考虑此解决方案:
/** * 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'}); ````
以上是如何使用表单在 JavaScript 中提交 POST 请求?的详细内容。更多信息请关注PHP中文网其他相关文章!