在 Jquery 变量中使用 PHP


Using PHP in Jquery Variable

我正在尝试使用Ajax格式化Wordpress评论列表中的新评论。这是我正在处理的代码片段。

全文可以在这里找到: http://pastebin.com/UHnPgf4J

success: function(data, textStatus){
if(data=="success"){
var avatar = <?php echo get_avatar( $comment, 32 ); ?>;
var author =  <?php the_author_meta( 'user_url'); ?>;
var timestamp = <?php printf(__('%1$s at %2$s'), get_comment_date(),  get_comment_time()) ?>;
var commenttext =  jQuery('#comment').val();
jQuery('<li>'+'<div class="comment-author vcard">'+avatar+
      '<div class="comment-meta">'+author+'</div>'+
      '<div class="comment-time-stamp">'+timestamp+'</div>'+
      '<div class="comment-text">'+commenttext+'</div>'+'</li>'+).insertBefore(respond);
statusdiv.html('<p class="ajax-success" >Thanks for your comment. We appreciate your response.</p>');
}

唯一有效的是"注释文本",因为它没有 php。其他的("头像"作者"和"时间戳")在Firebug中都返回错误。

我尝试了一些我找到的建议,但无法正常工作。任何帮助将不胜感激。

<?php ... ?>标签周围缺少引号

试试这个:

success: function(data, textStatus){
  if(data=="success"){
    var avatar = "<?php echo get_avatar( $comment, 32 ); ?>";
    var author =  "<?php the_author_meta( 'user_url'); ?>";
    var timestamp = "<?php printf(__('%1$s at %2$s'), get_comment_date(),  get_comment_time()) ?>";
    var commenttext =  jQuery('#comment').val();
    jQuery('<li>'+'<div class="comment-author vcard">'+avatar+
    '<div class="comment-meta">'+author+'</div>'+
    '<div class="comment-time-stamp">'+timestamp+'</div>'+
    '<div class="comment-text">'+commenttext+'</div>'+'</li>'+).insertBefore(respond);
    statusdiv.html('<p class="ajax-success" >Thanks for your comment. We appreciate your response.</p>');
  }
}

在 Javascript 中,您应该用双引号将字符串值括起来。
喜欢这个:

var author =  "<?php the_author_meta( 'user_url'); ?>";