为什么单击一个按钮会影响 jQuery Ajax 中的所有按钮


Why Clicking One Button Affects All Buttons in jQuery Ajax

我想点击一个影响(将某些内容发布到我们的 API)其特定 id 的按钮。但是,当我单击它时,页面的整个按钮将数据发送到我们的API。这是我页面的小快照。如您所见,所有行都有唯一的 id,但是当我单击行中的相对投票按钮时,它会对所有行进行投票。

我的jQuery和Ajax代码在这里

jQuery in First.php

            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>";

阿贾克斯.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>

那么在你的函数上,yu 可以用 jQuery 的数据函数获取 id

var poll_id = $(this).data("poll-id")

并像现在一样进行Ajax调用

因为您的选择器选择所有按钮而不是特定按钮。

 echo "$('body').on('click', 'button', function(event){";

您应该使用 class(.) 或 id(#) 前缀。