Home > Web Front-end > JS Tutorial > How Can I Simulate an HTML Form POST Submission Using JavaScript?

How Can I Simulate an HTML Form POST Submission Using JavaScript?

Mary-Kate Olsen
Release: 2024-12-27 22:32:14
Original
522 people have browsed it

How Can I Simulate an HTML Form POST Submission Using JavaScript?

Simulating HTML Form Submission via JavaScript POST Request

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:

  1. Create a Form Element:

    const form = document.createElement('form');
    form.method = 'post';
    form.action = path;
    Copy after login
  2. 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);
      }
    }
    Copy after login
  3. Append Form and Submit:

    document.body.appendChild(form);
    form.submit();
    Copy after login

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

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!

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