为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
MMTTMM 2023-07-08 15:40:30
我什至不确定我的标题是否正确。无论如何,我正在创建一个页面,用户可以在其中提交消息/帖子,目前正在尝试找出如何使用短轮询(即 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!<?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  = "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}
查看完整描述

1 回答

?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

首先,您需要某种表格来匹配帖子的喜好。然后你就可以更新相应帖子的div的内容了.likes。


又快又脏


由于您的 PHP 已经返回"1, 2, 0"posts和的字符串1,因此只需在 Javascript 中简单地拆分该字符串,然后按顺序更新 div 即可:23.likes


success: function(data) {

  var likes = data.split(", "); // likes will hold ["1", "2", "0"]

  $('.likes').each(function(i, likeDiv) {

    $(likeDiv).text(likes[i]);

  });

}

这适用于您的特定情况,但依赖于这样一个事实:您的 HTML 的排序方式与您的帖子在数据库中的排序方式完全相同。所以不太有弹性。


相反,我建议您更改 PHP,使其同时具有点赞数和帖子 ID,并将整个内容作为 JSON 进行回显


JSON


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


// build output collection

$output = [];

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

    $output[] = [

        'post_id' => $row['post_id'],

        'likes'   => $row['total_likes']

    ];

}


echo json_encode($output);

// [{"post_id": 1, "likes": 1}, {"post_id": 2, "likes": 2}, {"post_id": 3, "likes": 0}]'

?>

JS


success: function(data) {

  var postsLikes = JSON.parse(data);

  for (var i = 0; i < postsLikes.length; i++) {


    // find corresponding post

    var $post = $('.postid').filter(function(j, postIdDiv) {

      return postIdDiv.textContent == postsLikes[i].post_id

    }).parent()


    // update likes count in post

    $post.find('.likes').text(postsLikes[i].likes)

  }

}


查看完整回答
反对 回复 2023-07-08
  • 1 回答
  • 0 关注
  • 73 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信