且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-04-17 05:36:19

在表单中动态创建并提交

/**
 * 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.