POST Request in JavaScript Like Form Submission
Seeking to redirect a browser to a different page, a GET request can be used, as in the example below:
document.location.href = 'http://example.com/q=a';
However, for resources that require a POST request, a different approach is necessary. HTML can be used for static submissions, as shown:
<form action="http://example.com/" method="POST"> <input type="hidden" name="q" value="a"> </form>
On the other hand, a JavaScript solution is preferred for dynamic submissions:
post_to_url('http://example.com/', {'q':'a'});
Cross-browser compatibility requires a comprehensive implementation. The following code provides a straightforward 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') { // The rest of this code assumes you are not using a library. // It can be made less verbose if you use one. const form = document.createElement('form'); form.method = method; form.action = path; 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); } } document.body.appendChild(form); form.submit(); }
Example usage:
post('/contact/', {name: 'Johnny Bravo'});
This method ensures that the browser location changes, simulating form submission. Note that the hasOwnProperty check has been added to prevent inadvertent bugs.
The above is the detailed content of How Can I Simulate a POST Request in JavaScript Like a Form Submission?. For more information, please follow other related articles on the PHP Chinese website!