JavaScript post 请求就像表单提交一样 [英] JavaScript post request like a form submit

查看:29
本文介绍了JavaScript post 请求就像表单提交一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将浏览器定向到不同的页面.如果我想要一个 GET 请求,我可能会说

I'm trying to direct a browser to a different page. If I wanted a GET request, I might say

document.location.href = 'http://example.com/q=a';

但是除非我使用 POST 请求,否则我尝试访问的资源将无法正确响应.如果这不是动态生成的,我可能会使用 HTML

But the resource I'm trying to access won't respond properly unless I use a POST request. If this were not dynamically generated, I might use the HTML

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

然后我会从 DOM 提交表单.

Then I would just submit the form from the DOM.

但我真的希望 JavaScript 代码可以让我说

But really I would like JavaScript code that allows me to say

post_to_url('http://example.com/', {'q':'a'});

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

What's the best cross browser implementation?

编辑

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

I'm sorry I was not clear. I need a solution that changes the location of the browser, just like submitting a form. If this is possible with XMLHttpRequest, it is not obvious. And this should not be asynchronous, nor use XML, so Ajax is not the answer.

推荐答案

在表单中动态创建并提交

/**
 * 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 检查以修复任何无意中的错误.

EDIT: Since this has gotten upvoted so much, I'm guessing people will be copy-pasting this a lot. So I added the hasOwnProperty check to fix any inadvertent bugs.

这篇关于JavaScript post 请求就像表单提交一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆