Ajax JQuery - 将返回的变量 + 输入按钮和跨度附加到 Div

Ajax JQuery - Append Returned Variables + Input Button and Span to Div

使用 Ajax 请求中的变量创建一个输入按钮和 span 标签,显示每个 post 的点赞数(这是用于留言板),但是串联使用 JQuery 的字段超出了我的范围。以前只使用 php/html 就可以工作,但想使用 Ajax/JQuery.

使它更干净

尝试使用 JQuery 实现以下逻辑:

<div class="content">
  <div class="post-action">

<input type="button" value="Like" id="like_<?php echo $ID . "_" . $UserID; ?>" class="like" style="<?php if($type == 1){ echo "color: #ffa449;"; } ?>" />&nbsp;(<span id="likes_<?php echo $ID . "_" . $UserID; ?>"><?php echo $total_likes; ?></span>)&nbsp;
  </div>
</div>

JQuery 基本尝试,但确实不确定 syntax/logic(未在页面上填充 html,但 Ajax 请求有效):

success: function(response) {

$(".content").html("")
for( var key of Object.keys( response ) ) {
$( '.content' ).append( `<div class="post-action">
    <input type="button" value="Like" id="like_${response[key].ID}_${response[key].UserID}></div>`);    
    }
 }

JSON 从 Ajax 请求返回的数组数据:

$data[] = array ( 'ID' => $row['ID'], 'UserID' => $row['UserID'], 'UserIDLikeChk' => $row['UserIDLikeChk'], 'MessageText' => nl2br(htmlentities($row['MessageText'],ENT_COMPAT|ENT_IGNORE, "UTF-8") ), 'cntLikes' => $row['cntLikes'], 'Type' => $row['Type'] );

已更新 数据结构:

    success: function(response) {
    $(".content").html("");
      $.each(response, function() {
          $.each($(this), function(i, item) {
var mycss =(item.Type == 1) ? ' style="color: #ffa449;"' :'';
              $( '.content' ).append( '<div class="post-action"><input '+mycss+' type="button" value="Like" id="like_'+item.ID+'_'+item.UserID+'"><span id="likes_'+item.ID+'_'+item.UserID+'">'+item.cntLikes+'</span></div>');
          });
      });
    }

在您的代码中,字符串和变量没有分开地混合在一起。 Javascript 中的 + 字符是点 (.) 的替代字符,用于 pHp 中的字符串连接。

并且最好在附加内容时避免换行。

我不得不在 pHp 中对您的数组进行编码,以了解您得到的是什么,我仍然不确定,但我假设您可以接收多个对象。

并且不要忘记将 dataType: 'json', 添加到您的 ajax 选项中。