Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

[Javascript]使用Javascript來實作POST的submit

內容目錄

使用Javascript來實作POST的submit

這個做法應該滿多人知道的,也算是一種老派做法了吧,現在前端框架不太需要這樣處理XDDD沒關係就當作筆記。因為需求關係,想在流程最後加上一個submit行為以POST方式打資料到某個位置,左想右想在我遇到的狀況中還是以Javascript來實踐比較,於是翻找到這個老派作法。

現在說到用Javascript來處理POST或GET,直接就會想到ajax或是$.post/$.get之類,好啦,jQuery也算老了,還有axios等等方式,但我需要打一個資料到目標後執行一段php函式並且打開新分頁,因為不想用jQuery來實作,左思右想,找到了這個做法。哎呀,怎麼沒想到這麼簡單的方式勒XDD

概念很簡單,用Javascript建立一個隱藏的form,然後填入資料執行他,就這麼簡單。範例如下

/**
 * 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;
  form.target = ''_blank '';  //如果要開新分頁

  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('/target/', {email: 'xxxx@mail'});