javascript - 当<form>中定义了多个&lt;input&gt;时,如何知道提交的是哪个&lt;input&gt;?

标签 javascript ajax forms form-data xmlhttprequest-level2

我想实现下面的简单 JavaScript 函数 submitForm()基于XMLHttpRequestFormData 。此功能在第一个 <form> 上运行良好但第二个失败:该函数应该使用 input.formaction而不是form.action

如何检测按下的<input>并检索相应的formaction

( 大多数 SO 答案建议使用框架(如 jquery)进行此类处理。但我认为仅学习纯 JavaScript 比学习 JS 框架更容易。如果您确信使用框架可以更简单地编写此代码片段,请提出您的版本。请解释为什么您建议的框架在这​​种情况下是相关的/相关的/适合的。我可能决定学习您最喜欢的 JS 框架... 编辑: 我发现了这个类似的问题:JQuery get formaction and formmethod)

<!DOCTYPE html>
<html>

<head>
<script>
function submitForm(form)
{
  var xhr = new XMLHttpRequest();
  xhr.onload = function() { alert (xhr.responseText); }
  xhr.open ("post", form.action, true);
  xhr.send (new FormData (form));
  return false;
}
</script>
</head>

<body>
<form action="first.php" onsubmit="submitForm(this);">
   <fieldset>
      <legend>First</legend>
      <input type="text" name="data" />
      <input type="submit"  />
   </fieldset>
</form>

<form onsubmit="submitForm(this);">
   <fieldset>
      <legend>Second</legend>
      <input type="text" name="data" />
      <input type="submit" value="A" formaction="second-A.php" />
      <input type="submit" value="B" formaction="second-B.php" />
   </fieldset>
</form>
</body>
</html>

(在阅读 XMLHttpRequest to Post HTML FormSending POST data with a XMLHttpRequest 和优秀的 MDN documentation 后,我实现了这个代码片段。)

最佳答案

我建议在 JavaScript 中设置事件监听器,以便您可以访问 Event 对象。

function submitForm(e) {
  // Get the DOM element that submitted the form
  var caller = e.target || e.srcElement;
  // Set the action to 'formaction' attribute of the caller if it exists, otherwise use the action of the form the caller is in
  var action = caller.getAttribute("formaction") || caller.form.action;

  // This is your code, I just changed the variable name for the action to 'action'.
  var xhr = new XMLHttpRequest();
  xhr.onload = function() { alert (xhr.responseText); }
  xhr.open ("post", action, true);
  xhr.send (new FormData (form));
}

// Get all forms
var forms = document.querySelectorAll("form");

// Iterate over the forms
for (var i = 0; i < forms.length; ++i) {
  // Set the event listener
  forms.item(i).onsubmit = submitForm;
}

关于javascript - 当<form>中定义了多个&lt;input&gt;时,如何知道提交的是哪个&lt;input&gt;?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19840154/

相关文章:

javascript - Bootstrap 画廊网格

javascript - AJAX Date 无法正确显示日期

jquery - 在 JQuery load() 之前运行动画

forms - API中application/x-www-form-urlencoded POST请求参数的字符编码(非Form)

javascript - 检查是否在下拉多项选择中选择了多个选项

javascript - 纯JS和html跨域ajax到外域

javascript - Protractor 中的全局 beforeEach 和 afterEach

javascript - jquery ajax 未在 codeigniter 中发送数据

forms - Symfony2 : populating select list from a yaml file

javascript - 如果输入值为空,则使用 Javascript 分配一个值 "empty"