我在同一页面上有两个类似的表单,希望对同一个Flask函数进行ajax调用。如何从单击按钮的表单中获取数据?我尝试使用document.getElementsByName()
获取提交表单中的元素值,然后将其包含在要通过ajax发送的数据中:
<script type="text/javascript" src="jquery.js"></script>
<form name="contact1" id="contact1">
<div>Name: <input type="text" name="name" id="name1" required /></div>
<div>Email: <input type="email" name="email" id="email1" required /></div>
<div><input type="submit" name="submit" value="Submit" /></div>
</form>
<form name="contact2" id="contact2">
<div>Name: <input type="text" name="name" id="name2" required /></div>
<div>Email: <input type="email" name="email" id="email2" required /></div>
<div><input type="submit" name="submit" value="Submit" /></div>
</form>
<div id="results"></div>
<script type="text/javascript">
$(document).ready(function() {
$("form").submit(function() {
var name = document.getElementsByName("name")[0].value;
var email = document.getElementsByName("email")[0].value;
$.ajax({
type: "POST",
url: '/contact',
data: {
name: name,
email: email
},
success: function (data) {
$('#results').html(data);
},
error: function(jqXHR, text, error){
$('#result').html(error);
}
});
return false;
});
});
</script>
答案 0 :(得分:1)
使用jQuery:
var name = $("[name=name]",this).val();
- 或者给他们上课并使用$(".name",this).val()
重命名提交按钮 - name =&#34;提交&#34;将隐藏表单的提交方法
使用preventDefault()实际上不提交表单
$(function() {
$("form").on("submit", function(e) {
e.preventDefault(); // stop submission
var name = $("[name=name]",this).val(); // the field that belongs to "this" form
var email = $("[name=email]",this).val();
$.ajax({
type: "POST",
url: '/contact',
data: {
name: name,
email: email
},
success: function(data) {
$('#results').html(data);
},
error: function(jqXHR, text, error) {
$('#result').html(error);
}
});
});
});