我想实现下面的简单 JavaScript 函数 submitForm()
基于XMLHttpRequest
和FormData
。此功能在第一个 <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 Form 、 Sending 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>中定义了多个<input>时,如何知道提交的是哪个<input>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19840154/