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

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

Edit

对不起,我没说清楚.我需要一个解决方案来更改浏览器的位置,就像提交表单一样.如果XMLHttpRequest可以做到这一点,那就不明显了.而且这不应该是异步的,也不应该使用XML,所以Ajax不是答案.

推荐答案

Dynamically create <input>s in a form and submit it

/**
 * 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'});

EDIT:由于这一点得到了如此多的支持,我猜人们会大量复制粘贴这一点.所以我添加了hasOwnProperty个判断,以修复任何无意中出现的错误.

Javascript相关问答推荐

试图为每支球队生成类似于2024/25年欧洲足联冠军联赛瑞士系统格式的独特比赛配对

在贝塞尔曲线的直线上找不到交叉点:(使用@Pomax的bezier.js)

jQuery提交按钮重新加载页面,即使在WordPress中使用preventDefault()

如何在angular中从JSON值添加动态路由保护?

Angular 17—每当一个布尔变量变为真时触发循环轮询,只要它保持为真

colored颜色 检测JS,平均图像 colored颜色 检测JS

如何将多维数组插入到另一个多维数组中?

在浏览器中触发插入事件时检索编码值的能力

使用getBorbingClientRect()更改绝对元素位置

按什么顺序接收`storage`事件?

无法设置RazorPay订阅API项目价格

Node.js错误: node 不可单击或不是元素

我正在试着做一个TicTacToe Ai来和我玩.但是,我试着在第一个方块被点击时出现一个X,然后在第二个方块之后出现一个O

用Reaction-RT-Chart创建实时条形图

JQuery使用选项填充HTMLSELECT并设置默认结果,默认结果显示为空

在Press Reaction本机和EXPO av上播放单个文件

Firebase函数中的FireStore WHERE子句无法执行

AstroJS混合模式服务器终结点返回404

使用静态函数保存 node 前的钩子

在对象的嵌套数组中添加两个属性