首頁 >web前端 >js教程 >如何使用 JavaScript 動態提交 POST 請求?

如何使用 JavaScript 動態提交 POST 請求?

Patricia Arquette
Patricia Arquette原創
2024-12-20 21:46:13661瀏覽

How to Dynamically Submit a POST Request Using JavaScript?

建立動態表單並提交 POST 請求

在 JavaScript 中,我們經常需要使用 POST 請求將資料傳送到伺服器。但是,如果資源需要表單提交才能得到正確的回應,我們需要一種動態模擬表單提交的方法。

使用 XMLHttpRequest

XMLHttpRequest 是用於非同步 HTTP 請求。但是,它對於提交表單來說並不理想,因為它不是為原生處理表單資料而設計的。

動態建立輸入元素

跨瀏覽器解決方案涉及動態建立輸入元素並將它們附加到表格中。然後我們可以透過程式提交此表單。

/**
 * 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') {
  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();
}

用法

您可以使用此函數透過動態建立和提交表單來傳送 POST 要求:

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

以上是如何使用 JavaScript 動態提交 POST 請求?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn