[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"blog-javascript使用javascript來實作post的submit":3},{"id":4,"slug":5,"title":6,"description":7,"content":8,"date":9,"image":10,"imageAlt":6,"author":11,"categories":14,"path":17,"minRead":18},179,"javascript使用javascript來實作post的submit","[Javascript]使用Javascript來實作POST的submit","使用Javascript來實作POST的submit 這個做法應該滿多人知道的，也算是一種老派做法了吧，現在前 […]","\u003Ch1>使用Javascript來實作POST的submit\u003C\u002Fh1>\n\u003Cp>這個做法應該滿多人知道的，也算是一種老派做法了吧，現在前端框架不太需要這樣處理XDDD沒關係就當作筆記。因為需求關係，想在流程最後加上一個submit行為以POST方式打資料到某個位置，左想右想在我遇到的狀況中還是以Javascript來實踐比較，於是翻找到這個老派作法。\u003C\u002Fp>\n\u003Cp>現在說到用Javascript來處理POST或GET，直接就會想到ajax或是$.post\u002F$.get之類，好啦，jQuery也算老了，還有axios等等方式，但我需要打一個資料到目標後執行一段php函式並且打開新分頁，因為不想用jQuery來實作，左思右想，找到了這個做法。哎呀，怎麼沒想到這麼簡單的方式勒XDD\u003C\u002Fp>\n\u003Cp>概念很簡單，用Javascript建立一個隱藏的form，然後填入資料執行他，就這麼簡單。範例如下\u003C\u002Fp>\n\u003Cpre>\u003Ccode>\u002F**\n * sends a request to the specified url from a form. this will change the window location.\n * @param {string} path the path to send the post request to\n * @param {object} params the parameters to add to the url\n * @param {string} [method=post] the method to use on the form\n *\u002F\n\nfunction post(path, params, method=&#039;post&#039;) {\n\n  const form = document.createElement(&#039;form&#039;);\n  form.method = method;\n  form.action = path;\n  form.target = &#039;&#039;_blank &#039;&#039;;  \u002F\u002F如果要開新分頁\n\n  for (const key in params) {\n    if (params.hasOwnProperty(key)) {\n      const hiddenField = document.createElement(&#039;input&#039;);\n      hiddenField.type = &#039;hidden&#039;;\n      hiddenField.name = key;\n      hiddenField.value = params[key];\n\n      form.appendChild(hiddenField);\n    }\n  }\n\n  document.body.appendChild(form);\n  form.submit();\n}\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cp>最後記得要執行。\u003C\u002Fp>\n\u003Cpre>\u003Ccode>post(&#039;\u002Ftarget\u002F&#039;, {email: &#039;xxxx@mail&#039;});\u003C\u002Fcode>\u003C\u002Fpre>\n","2022-12-20T18:00:12","",{"name":12,"link":13},"Chih Fan","http:\u002F\u002Fpost.billxu.net",[15],{"name":16,"slug":16},"frontend","\u002Fblog\u002Fjavascript使用javascript來實作post的submit",1]