我想单击一个按钮来影响(向我们的 API 发布某些内容)其特定 ID。但是,当我单击它时,页面的整个按钮都会将数据发送到我们的 API。 Here is the little snapshot of my page 。如您所见,所有行都有唯一的 ID,但是当我单击该行中的相对投票按钮时,它会对所有行进行投票。
我的 jQuery 和 Ajax 代码在这里
First.php 中的 jQuery
public function getButtons() {
$ids = $this->polls_id;
echo $this->polls_id;
echo "<html>";
echo "<head>";
echo '<meta charset="utf-8">';
echo '<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>';
echo '<script type="text/javascript"></script>';
echo '<script type="text/javascript">';
echo '$(function(){';
echo "$('body').on('click', 'button', function(event){";
echo "event.preventDefault();";
echo "var pollss_id = $('#" . $ids . "').text();";
echo "$.ajax({";
echo "method: 'POST',";
echo "url: 'ajax.php',";
echo "data: {'pollss_id' : pollss_id}";
echo "})";
echo "});";
echo "});";
echo "</script>";
echo "</head>";
echo "<body>";
echo '<div id='. $ids .'>' . $ids . '</div>';
echo '<button type="button">Vote</button>';
echo "</body>";
echo "</html>";
Ajax.php
<?php
session_start();
$user_id = $_SESSION['user_id'];
if($_POST) {
$polls_id = $_POST['pollss_id'];
}
function vote_poll1($user_id, $polls_id){
$postdata = http_build_query(
array(
'user_id' => $user_id,
'poll_id' => $polls_id,
'vote_value' => '1'
)
);
$opts = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://sitename.herokuapp.com/api/v1/polls/'. $polls_id . '/castvote', false, $context);
}
echo vote_poll1($user_id, $polls_id);
PS:我使用 for 循环创建对象并调用函数(图片、文本字段、按钮)。这可能会出现什么问题?
最佳答案
您现在的做法是在每个按钮上注册一个点击事件。
所以代码
$('#" . $ids . "').text();
将在单击任何按钮时运行。
您可以做的就是添加该函数一次并将 pollid 作为数据属性添加到按钮本身
<button data-poll-id="5" type="button">Vote</button>
然后在你的函数上你可以使用 jQuery 的数据函数获取 id
var poll_id = $(this).data("poll-id")
并像现在一样进行 ajax 调用
关于javascript - 为什么单击一个按钮会影响 jQuery Ajax 中的所有按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35314741/