我正在尝试将浏览器指向另一个页面。如果我想要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不是答案。


当前回答

不可以。您不能像提交表单一样提交JavaScript发布请求。

您可以拥有HTML格式的表单,然后使用JavaScript提交它。(如本页多次所述)。

您可以自己创建HTML,不需要JavaScript来编写HTML。如果有人这样建议,那就太傻了。

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

您的函数将按照您想要的方式配置表单。

function postToURL(a,b,c){
    document.getElementById("ninja").action     = a;
    document.getElementById("donaldduck").name  = b;
    document.getElementById("donaldduck").value = c;
    document.getElementById("ninja").submit();
}

然后,像这样使用它。

postToURL("http://example.com/","q","a");

但我会省略函数,只做。

document.getElementById('donaldduck').value = "a";
document.getElementById("ninja").submit();

最后,样式决定在ccs文件中。

#ninja { 
    display: none;
}

就我个人而言,我认为表格应该用名字来称呼,但现在这并不重要。

其他回答

@Aaron回答的一个简单而快速的实现:

document.body.innerHTML += '<form id="dynForm" action="http://example.com/" method="post"><input type="hidden" name="q" value="a"></form>';
document.getElementById("dynForm").submit();

当然,您应该使用JavaScript框架,如Prototype或jQuery。。。

使用此答案中提供的createElement函数,这是必要的,因为IE在使用document.createElement正常创建的元素上使用name属性时会中断:

function postToURL(url, values) {
    values = values || {};

    var form = createElement("form", {action: url,
                                      method: "POST",
                                      style: "display: none"});
    for (var property in values) {
        if (values.hasOwnProperty(property)) {
            var value = values[property];
            if (value instanceof Array) {
                for (var i = 0, l = value.length; i < l; i++) {
                    form.appendChild(createElement("input", {type: "hidden",
                                                             name: property,
                                                             value: value[i]}));
                }
            }
            else {
                form.appendChild(createElement("input", {type: "hidden",
                                                         name: property,
                                                         value: value}));
            }
        }
    }
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

接受的答案将像提交本地表单一样重新加载页面。此修改版本将通过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();
}

这将是使用jQuery选择的答案的一个版本。

// Post to the provided URL with the specified parameters.
function post(path, parameters) {
    var form = $('<form></form>');

    form.attr("method", "post");
    form.attr("action", path);

    $.each(parameters, function(key, value) {
        var field = $('<input></input>');

        field.attr("type", "hidden");
        field.attr("name", key);
        field.attr("value", value);

        form.append(field);
    });

    // The form needs to be a part of the document in
    // order for us to be able to submit it.
    $(document.body).append(form);
    form.submit();
}

这在我的情况下非常有效:

document.getElementById("form1").submit();

您可以在以下函数中使用它:

function formSubmit() {
     document.getElementById("frmUserList").submit();
} 

使用此选项,您可以发布所有输入值。