Home > Web Front-end > JS Tutorial > How Can I Simulate a POST Request in JavaScript Like a Form Submission?

How Can I Simulate a POST Request in JavaScript Like a Form Submission?

Mary-Kate Olsen
Release: 2024-12-18 15:29:11
Original
210 people have browsed it

How Can I Simulate a POST Request in JavaScript Like a Form Submission?

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';
Copy after login

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>
Copy after login

On the other hand, a JavaScript solution is preferred for dynamic submissions:

post_to_url('http://example.com/', {'q':'a'});
Copy after login

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();
}
Copy after login

Example usage:

post('/contact/', {name: 'Johnny Bravo'});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template