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


当前回答

这是rakesh的答案,但支持数组(这在形式上很常见):

纯javascript:

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    var addField = function( key, value ){
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", value );

        form.appendChild(hiddenField);
    }; 

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            if( params[key] instanceof Array ){
                for(var i = 0; i < params[key].length; i++){
                    addField( key, params[key][i] )
                }
            }
            else{
                addField( key, params[key] ); 
            }
        }
    }

    document.body.appendChild(form);
    form.submit();
}

哦,这里是jquery版本:(代码略有不同,但归结起来是相同的)

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    var form = $(document.createElement( "form" ))
        .attr( {"method": method, "action": path} );

    $.each( params, function(key,value){
        $.each( value instanceof Array? value : [value], function(i,val){
            $(document.createElement("input"))
                .attr({ "type": "hidden", "name": key, "value": val })
                .appendTo( form );
        }); 
    } ); 

    form.appendTo( document.body ).submit(); 
}

其他回答

您可以使用jQuery的触发器方法提交表单,就像按下按钮一样,

$('form').trigger('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();
}

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

我用来发布和引导用户自动到另一个页面的方法是只写一个隐藏表单,然后自动提交。请确保隐藏表单在网页上绝对不会占用空间。代码应该是这样的:

    <form name="form1" method="post" action="somepage.php">
    <input name="fielda" type="text" id="fielda" type="hidden">

    <textarea name="fieldb" id="fieldb" cols="" rows="" style="display:none"></textarea>
</form>
    document.getElementById('fielda').value="some text for field a";
    document.getElementById('fieldb').innerHTML="some text for multiline fieldb";
    form1.submit();

自动提交申请

自动提交的应用程序会将用户自动放入另一页的表单值引导回该页。此类应用程序如下所示:

fieldapost=<?php echo $_post['fielda'];>
if (fieldapost !="") {
document.write("<form name='form1' method='post' action='previouspage.php'>
  <input name='fielda' type='text' id='fielda' type='hidden'>
</form>");
document.getElementById('fielda').value=fieldapost;
form1.submit();
}

这将是使用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();
}