JavaScript发布请求,例如表单提交

JavaScript发布请求,例如表单提交,第1张

JavaScript发布请求,例如表单提交 动态创建
<input>
表单并提交
function post(path, params, method='post') {  // The rest of this pre assumes you are not using a library.  // It can be made less wordy 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
检查以修复所有无意的错误。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5009149.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存