ブラウザを別のページに誘導しようとしています。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'});
最適なクロスブラウザ実装は何ですか?
フォームを送信するのと同じように、ブラウザの位置を変更するソリューションが必要です。これが可能であればXMLHttpリクエスト、それは明らかではありません。また、これは非同期ではなく、XML も使用しないため、Ajax は答えではありません。
ベストアンサー1
<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'});
編集: この投稿に多くの賛成票が集まったので、多くの人がこれをコピー&ペーストするだろうと推測します。そのため、hasOwnProperty
不注意によるバグを修正するためのチェックを追加しました。