1. ホーム
  2. javascript

[解決済み] フォーム送信のようなJavaScriptのポストリクエスト

2022-03-19 11:25:09

質問

ブラウザを別のページに誘導しようとしています。もし、GETリクエストをしたいのであれば、次のように言うかもしれません。

document.location.href = 'http://example.com/q=a';

しかし、私がアクセスしようとしているリソースは、POSTリクエストを使用しない限り、適切に応答してくれません。もしこれが動的に生成されないのであれば、私はHTMLの

<form action="http://example.com/" method="POST">
  <input type="hidden" name="q" value="a">
</form>

そうすると、DOMからフォームを送信するだけになりますね。

しかし、本当は次のようなJavaScriptのコードが欲しいのです。

post_to_url('http://example.com/', {'q':'a'});

クロスブラウザでの最適な実装は?

編集

分かりにくくて申し訳ありません。フォームを送信するように、ブラウザの場所を変更するソリューションが必要です。もし、これが XMLHttpRequest が、明らかではありません。そして、これは非同期であってはならないし、XMLを使用してはならないので、Ajaxは答えではありません。

どのように解決するのか?

動的に作成する <input> をフォームで送信します。

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

  // The rest of this code assumes you are not using a library.
  // It can be made less verbose if you use one.
  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('/contact/', {name: 'Johnny Bravo'});

EDIT : これだけupvotedされているのだから、みんなこれをコピーペーストしているのだろう。そこで、私は hasOwnProperty をチェックし、不用意なバグを修正しました。