我在许多表单中使用ajax,问题是当我输入其中一种表单时,返回的消息将显示在所有表单中,因此有一种避免这种情况的方法,因此仅在表单中显示消息发送,而不是其他人发送?
这是输入的html改编:
<!-- FORM 1-->
<form name="name" action="form.php" method="POST" id="contact1">
<li class="text-info">Name</li>
<select name="age">
<option value="Sam">Sam</option>
<option value="Mike">Mike</option>
</select>
<input type="submit" name="submit" value="namevalue">
</form>
<div id="result1"></div>
<!-- FORM 2-->
<form name="likes" action="form.php" method="POST" id="contact2">
<ul>
<li class="text-info">Interests</li>
<input type="checkbox" name="interests[]" value="play_soccer">Play Soccer</input>
<input type="checkbox" name="interests[]" value="play_golf">Play Golf</input>
<input type="submit" name="submit" value="gamevalue">
</form>
<div id="result2"></div>
Ajax的js是:
<script type="text/javascript">
$(document).ready(function() {
$("form").submit(function() {
// Getting the form ID
var formID = $(this).attr('id');
var formDetails = $('#'+formID);
$.ajax({
type: "POST",
url: 'form.php',
data: formDetails.serialize(),
success: function (data) {
// Inserting html into the result div
$('#results1').html(data);
$('#results2').html(data);
},
});
return false;
});
});
</script>
因此在form.php中,当单独提交表单时,每个表单都会通过简单的回显发送消息,通知其已更新。
任何帮助表示欢迎,谢谢
答案 0 :(得分:0)
使用数据属性
$("form").on("submit", function(event) {
event.preventDefault()
const form = $(this);
const outputElem = $(form.data("output"))
outputElem.text(form.attr("id"))
console.log(form.serialize())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="name" action="form.php" method="POST" id="contact1" data-output="#result1">
<select name="age">
<option value="Sam">Sam</option>
<option value="Mike">Mike</option>
</select>
<input type="submit" name="submit" value="namevalue">
</form>
<div id="result1"></div>
<form name="name" action="form.php" method="POST" id="contact2" data-output="#result2">
<select name="age">
<option value="Sam">Sam</option>
<option value="Mike">Mike</option>
</select>
<input type="submit" name="submit" value="namevalue">
</form>
<div id="result2"></div>
答案 1 :(得分:0)
if(formID=='contact1')
$('#results1').html(data);
else if(formID=='contact2')
$('#results2').html(data);