我用 jQuery 制作了一个“有用按钮”,以便用户可以评价,例如问题的答案(例如 stackoverflow 上的 upvote 功能)。
function submitForm() {
var form = document.myform;
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url:'like_submit.php',
data: dataString,
success: function(data){
$('#myResponse').html(data);
$('#myResponse').fadeIn().delay(3000).fadeOut();
}
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" class="myform" method="post" name="myform">
Was this 1. answer helpful?
<input type="hidden" name="answer_id" value="1" />
<input class="label__checkbox" type="checkbox" name="helpful" onclick="submitForm()" />
</form>
<div id="myResponse"></div>
like_submit.php是这样的:
<?php
$helpful = $_POST['helpful'];
$answer_id = $_POST['answer_id'];
echo "Thank you! Helpful? $helpful | AnswerID: $answer_id";
?>
因此,对于一个答案来说,它是有效的。
但现在我想添加多个答案,但我不知道如何让脚本适用于这种情况。
如果我添加第二个表单...
<form id="myform" class="myform" method="post" name="myform">
Was this 2. answer helpful?
<input type="hidden" name="answer_id" value="2" />
<input class="label__checkbox" type="checkbox" name="helpful" onclick="submitForm()" />
</form>
<div id="myResponse"></div>
...我有两个问题。我只得到了最后一个 POST 数据。如果我单击第一个表格,它会显示: 谢谢你!有帮助吗?上 |答案编号:2
第二个问题,响应消息总是出现在第一位置。
有人可以帮忙吗?非常感谢!
最佳答案
获取与提交表单相关的元素
html:
onclick="submitForm(this)"
js:
function submitForm(el) {
var form = $(el).closest('form');
var dataString = form.serialize();
$.ajax({
type:'POST',
url:'like_submit.php',
data: dataString,
success: function(data){
form.next('#myResponse').html(data);
form.next('#myResponse').fadeIn().delay(3000).fadeOut();
}
});
return false;
}
function submitForm(el) {
var form = $(el).closest('form');
var dataString = form.serialize();
form.next('#myResponse').html(dataString);
form.next('#myResponse').fadeIn().delay(3000).fadeOut();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" class="myform" method="post" name="myform">
Was this 1. answer helpful?
<input type="hidden" name="answer_id" value="1" />
<input class="label__checkbox" type="checkbox" name="helpful" onclick="submitForm(this)" />
</form>
<div id="myResponse"></div>
<form id="myform" class="myform" method="post" name="myform">
Was this 2. answer helpful?
<input type="hidden" name="answer_id" value="2" />
<input class="label__checkbox" type="checkbox" name="helpful" onclick="submitForm(this)" />
</form>
<div id="myResponse"></div>
关于javascript - 同一页面上有多个有用的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47261393/