小编典典

JavaScript发布请求,例如表单提交

javascript

我正在尝试将浏览器定向到其他页面。如果我想要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并不是答案。


阅读 362

收藏
2020-04-22

共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 paramiters 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 wordy 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检查以修复所有无意的错误。

2020-04-22