我在许多表单中使用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 中,当单独提交表单时,每个表单都会发送带有简单回显的消息,通知其已更新。
欢迎任何帮助,谢谢
最佳答案
- 如果您不做任何更改,只需添加以下条件和成功响应即可
if(formID=='contact1')
$('#results1').html(数据);
else if(formID=='contact2')
$('#results2').html(数据);
关于javascript - Ajax 自定义表单内嵌消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55603097/