我正在尝试将浏览器指向另一个页面。如果我想要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'});

最好的跨浏览器实现是什么?

我需要一个改变浏览器位置的解决方案,就像提交表单一样。这不应该是异步的,也不应该使用XML,因此Ajax不是答案。


当前回答

这就像艾伦的选项2(上图)。如何实例化httpobj是一个练习。

httpobj.open("POST", url, true);
httpobj.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
httpobj.onreadystatechange=handler;
httpobj.send(post);

其他回答

您可以进行AJAX调用(可能使用Prototype.js或JQuery等库)。AJAX可以处理GET和POST选项。

您可以使用类似jQuery的库及其$.post方法。

FormObject是一个选项。但现在大多数浏览器都不支持FormObject。

如果安装了Prototype,则可以收紧代码以生成和提交隐藏表单,如下所示:

 var form = new Element('form',
                        {method: 'post', action: 'http://example.com/'});
 form.insert(new Element('input',
                         {name: 'q', value: 'a', type: 'hidden'}));
 $(document.body).insert(form);
 form.submit();

接受的答案将像提交本地表单一样重新加载页面。此修改版本将通过XHR提交:

function post(path, params) {
  const form = document.createElement('form');

  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);
    }
  }
  var button = form.ownerDocument.createElement('input');
  button.type = 'submit';
  form.appendChild(button);

  form.onsubmit = async function (e) {
    console.log('hi');

    e.preventDefault();
    const form = e.currentTarget;

    try {
      const formData = new FormData(form);
      const response = await fetch(path, {
        method: 'POST',
        body: formData,
      });

      console.log(response);
    } catch (error) {
      console.error(error);
    }
  };

  document.body.appendChild(form);
  button.click();
}