同一页面上的多个有用按钮

时间:2017-11-13 09:50:53

标签: javascript php jquery

我做了一个"有用按钮"使用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>
&#13;
&#13;
&#13;

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数据。如果我点击第一个表单,它会说: 谢谢!有用吗?在|答案ID:2

第二个问题,响应消息总是出现在第一个位置。

有人可以帮忙吗?非常感谢!

1 个答案:

答案 0 :(得分:1)

获取与提交的表单相关的元素

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>