如何将值从 php 数据返回到 ajax 成功

我什至不确定我的标题是否正确。无论如何,我正在创建一个页面,用户可以在其中提交消息/帖子,目前正在尝试找出如何使用短轮询(即 setinterval)在特定秒数内更新每个帖子的点赞数 - 这是有意为之现在。这只是一种做法,我知道我没有使用参数化查询,并且短轮询并不理想,但我现在将其搁置。这可能是我最长的帖子,抱歉,但我被告知这比提供半生不熟的输入/问题方便得多。


我有这个Jquery:


function refreshPostLikes() {

  var postid_array = []; //establish array for postid

  $(".post .postid").each(function () {

    //get id for each post

    var postid = $(this).attr("value");

    postid_array.push(postid); //place all the postid in an array

  });

  updatePostLikes(postid_array); //pass the array

}


function updatePostLikes(postid) {

  setInterval(function () {

    $.ajax({

      url: "/main/refresh-like.php",

      type: "post",

      data: { postid: postid }, //send postid array to php file

      success: function (data) {

        alert(data); //testing because I don't know how

      },

    });

  }, 20000); //just 20 seconds interval

}


refreshPostLikes(); //run function

这是我的PHP 文件,refresh-like.php!


<?php

require_once '../connection.php';


$postID = trim(json_encode($_POST['postid']), '[]'); //convert array to string and remove square brackets to be a valid value for MySQL query


$likeQuery  = "select count(*) as total_likes from likes where post_id in ('.$postID.') group by post_id order by post_id desc"; //query number of likes

$likeResult = mysqli_query($conn, $likeQuery);


while ($row = mysqli_fetch_assoc($likeResult)) { //loop through the query

    $likes = $row['total_likes'];


    echo $likes; //output number of likes per post and pass it to ajax data success

}

?>

使用上面的代码,如果我有三个帖子(混合有 1、2 和 0 个喜欢),Ajax 成功下的警报(如我指出的“正在测试,因为我不知道如何”)将显示一条消息:1、2 , 0,这是正确的!这些数字集中在一个警报中,仅供参考。


现在我的问题是如何将这些值传递回 Likes div 下的每个帖子?我的意思是postid1有1个赞,postid2有2个赞,postid3有0个赞。通常我选择单个元素并使用 .html 传递,但是如果返回的 php 数据是全部(即 2, 1, 0),该怎么办。我知道我需要在这里做出调整:


success: function(data) {

    alert(data); //testing because I don't know how

}


MMTTMM
浏览 75回答 1
1回答

慕无忌1623718

首先,您需要某种表格来匹配帖子的喜好。然后你就可以更新相应帖子的div的内容了.likes。又快又脏由于您的 PHP 已经返回"1, 2, 0"posts和的字符串1,因此只需在 Javascript 中简单地拆分该字符串,然后按顺序更新 div 即可:23.likessuccess: function(data) {&nbsp; var likes = data.split(", "); // likes will hold ["1", "2", "0"]&nbsp; $('.likes').each(function(i, likeDiv) {&nbsp; &nbsp; $(likeDiv).text(likes[i]);&nbsp; });}这适用于您的特定情况,但依赖于这样一个事实:您的 HTML 的排序方式与您的帖子在数据库中的排序方式完全相同。所以不太有弹性。相反,我建议您更改 PHP,使其同时具有点赞数和帖子 ID,并将整个内容作为 JSON 进行回显JSONPHP<?phprequire_once '../connection.php';$postID = trim(json_encode($_POST['postid']), '[]'); //convert array to string and remove square brackets to be a valid value for MySQL query$likeQuery&nbsp; = "select count(*) as total_likes from likes where post_id in ('.$postID.') group by post_id order by post_id desc"; //query number of likes$likeResult = mysqli_query($conn, $likeQuery);// build output collection$output = [];while ($row = mysqli_fetch_assoc($likeResult)) { //loop through the query&nbsp; &nbsp; $output[] = [&nbsp; &nbsp; &nbsp; &nbsp; 'post_id' => $row['post_id'],&nbsp; &nbsp; &nbsp; &nbsp; 'likes'&nbsp; &nbsp;=> $row['total_likes']&nbsp; &nbsp; ];}echo json_encode($output);// [{"post_id": 1, "likes": 1}, {"post_id": 2, "likes": 2}, {"post_id": 3, "likes": 0}]'?>JSsuccess: function(data) {&nbsp; var postsLikes = JSON.parse(data);&nbsp; for (var i = 0; i < postsLikes.length; i++) {&nbsp; &nbsp; // find corresponding post&nbsp; &nbsp; var $post = $('.postid').filter(function(j, postIdDiv) {&nbsp; &nbsp; &nbsp; return postIdDiv.textContent == postsLikes[i].post_id&nbsp; &nbsp; }).parent()&nbsp; &nbsp; // update likes count in post&nbsp; &nbsp; $post.find('.likes').text(postsLikes[i].likes)&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP