首页 > 解决方案 > 如何将php数组传递给ajax函数

问题描述

所以我想将这个表单 id 中的 php 数组值传递给我的 ajax 表单。一切正常,只是它只会显示 (1) id 号。这是我的表单代码:我将 $row[topic_id'] 作为值传递以获取 jquery 的 id。

public function forumview($query){
    $stmt = $this->db->prepare($query);
    $stmt->execute();
    $results = $stmt->fetchAll();

    if($stmt->rowCount()>0){
        foreach($results as $row){

            echo '<tr>';
            echo '<td style="color: #333;"><span class="pull-right">';

    //Problem is here with the $row['topic_id'] portion
    if(isset($_SESSION['user_session'])){
            echo '<a href="#" class="upVoteArrow" 
                   onclick="upVoteIncrementValue('.$row['topic_id'].');">';
        }else{                  
            echo '<a href="#" id="loginForm" class="upVoteArrow" data- 
                  toggle="modal" data-target="#loginModal"><i class="fa fa-arrow-up"></i> 
                  </a>';                
        }
         echo '<span id="voteCount">'.$this->cleanNumber($row['topic_likes']).'</span>';
      }

这是我的 Ajax 调用,用于将信息发送到我的 php 文件

function upVoteIncrementValue(postID){
   event.preventDefault();
    //var upVoteIncrement   = $("#upVoteIncrement").val();  //not needed

$.ajax({
        type: "POST",
        url: "voting.php",
        data:  {
            "upVoteIncrement": postID,
            },
        dataType: "json",
        cache: false,
        success: function(response){
            if(response){
                var response = $.trim(response);
                if(response){
                    $('#voteCount').html(response);
                }
                else {
                    return false;
                }
            }
        }
    });

然后这里是处理调用的 php 文件。

if(isset($_POST['upVoteIncrement'])){

$upVoteIncrement = $_POST['upVoteIncrement'];

$stmt = $conn->prepare('UPDATE topics SET topic_likes = topic_likes+1 WHERE topic_id = :id LIMIT 1');
$stmt->bindParam(':id', $upVoteIncrement);
$stmt->execute();


$upVote = $conn->prepare('SELECT topic_likes FROM topics WHERE topic_id = :id LIMIT 1');
$upVote->bindParam(':id', $upVoteIncrement);
$upVote->execute();
$upVoteCount = $upVote->fetchAll();

if($upVote->rowCount() > 0){
    foreach($upVoteCount as $row){

        $up = $row['topic_likes'];
        $results[] = $up;
        //exit();  //not needed
    }
}
echo json_encode($results);
}

本质上,我只是在制作一个简单的投票系统,用户单击它并以 1 为增量更新数据库。它增加了值并且一切正常,除了它只会为最后发布的项目增加它。因此,即使我对之前的某个主题进行投票,它也只会为最后插入的主题添加 1 票。任何建议都非常感谢,在此先感谢!

标签: phpjqueryajax

解决方案


如果您使用循环来填充行 ID,看起来您在这里是您的问题。

循环在循环的每次迭代中创建一个隐藏的输入元素,并且您没有更改元素的 id。因此,您将拥有一堆具有相同 id 的元素。这会以几种不同的方式给您带来问题。

我更改了您的 PHP 代码,以便每个元素都有自己的 ID。我还更改了您的 javascript 函数,以便将 id 值传递给函数本身。

看看这是否有帮助:

PHP:

if(isset($_SESSION['user_session'])){

  echo '<input type="hidden" id="' . $row['topic_id'] . '" name="upVoteIncrement" 
  value="' . $row['topic_id'] . '"><a href="#" class="upVoteArrow" 
  onclick="upVoteIncrementValue(' . $row['topic_id']  . ');">';

}

JS:

function upVoteIncrementValue(postID){
   event.preventDefault();
    //var upVoteIncrement = $("#upVoteIncrement").val(); //Don't need this anymore.

$.ajax({
        type: "POST",
        url: "voting.php",
        data:  {
            "upVoteIncrement": postID, //Use the passed value id value in the function.
            },
        dataType: "html",
        cache: false,
        success: function(response){
            if(response){
                var response = $.trim(response);
                if(response){
                    $('#voteCount').html(response);
                }
                else {
                    return false;
                }
            }
        }
    });

希望能帮助到你!

我还想在下面的代码中指出:

if($upVote->rowCount() > 0){
    foreach($upVoteCount as $row){

        $up = $row['topic_likes'];
        echo $up;
        exit();
    }
}

您将在循环的第一次迭代中退出脚本,您只会得到一个结果。

如果您需要返回一个数据数组,它应该如下所示:

if($upVote->rowCount() > 0){
    foreach($upVoteCount as $row){

        $up = $row['topic_likes'];
        $results[] =  $up;
        //exit(); 
    }
}

echo json_encode($results);

然后,您需要将数据类型设置为 json 而不是 html。

您的 ajax 中的响应现在将是一个数组。要查看数组:

success: function(response){
            if(response){
                console.log(response); //Look in your console to see your data.
                var response = $.trim(response);
                if(response){
                    $('#voteCount').html(response);
                }
                else {
                    return false;
                }
            }
        }

推荐阅读