Last active
May 26, 2023 00:38
-
-
Save zuzu/c68e105d966c4d235334 to your computer and use it in GitHub Desktop.
Formタグを作らずにJavascriptのみで通常のPOST送信をするための関数です。便利なのでgitsコード化して、どこでも使えるようにしておく。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* データをPOSTする | |
* @param String アクション | |
* @param Object POSTデータ連想配列 | |
* 記述元Webページ http://fujiiyuuki.blogspot.jp/2010/09/formjspost.html | |
* サンプルコード | |
* <a onclick="execPost('/hoge', {'fuga':'fuga_val', 'piyo':'piyo_val'});return false;" href="#">POST送信</a> | |
*/ | |
function execPost(action, data) { | |
// フォームの生成 | |
var form = document.createElement("form"); | |
form.setAttribute("action", action); | |
form.setAttribute("method", "post"); | |
form.style.display = "none"; | |
document.body.appendChild(form); | |
// パラメタの設定 | |
if (data !== undefined) { | |
for (var paramName in data) { | |
var input = document.createElement('input'); | |
input.setAttribute('type', 'hidden'); | |
input.setAttribute('name', paramName); | |
input.setAttribute('value', data[paramName]); | |
form.appendChild(input); | |
} | |
} | |
// submit | |
form.submit(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment