JavaScript post 请求,就像表单提交一样

2022-08-29 21:57:52

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


答案 1

在表单中动态创建 s 并提交<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


答案 2

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