繁体   English   中英

php中的jQuery ajax调用while循环仅返回第一个id

[英]jQuery ajax call in php while loop only returns first id

我正在研究wordpress插件,该插件每几秒钟更新一次股价。 我在html表格中显示股票价格,该表格在php循环中执行,该表格以wordpress帖子的形式获取股票。 在我的代码中,我需要帖子的标题,才能调用获取特定股价的函数。

<?php  $query = new WP_Query( $args );
   if ($query->have_posts()) :
     $i = 1;
   while ($query->have_posts()) : $query->the_post();
?>

<td class="name"><?php the_title(); ?></td>
<td class="price" id="<?php echo $i; ?>" value="<?php echo get_the_title(); ?>"></td>

我想将特定股票发布的ID传递给jQuery ajax函数。

jQuery(document).ready( function($){
   setInterval(callMe, 5000);
});

function callMe(){
  var id = $('.price').attr("id");
  var titleInput = jQuery('#' + id).attr("value");

  $.ajax({
         type: 'POST',
         url: ajax_object.ajaxurl,
         dataType: 'json',
         data: {
              action: 'myaction',
              post_title: titleInput
         },
         success: function(response){
                    $('#' + id).html(response);
     }
 });
}

这仅返回第一个id,然后也仅传递第一个帖子标题,而不传递其他帖子标题。

问题仅在于我如何调用ID吗? 我在玩我如何调用var id的方法,但是无法使其正常工作。

var id = $('.price').attr("id");

如果您对如何解决此问题有任何建议,请提供帮助。

$('.price')返回一个集合,虽然有一些函数(例如.css() )直接在它们上进行操作,但是.attr()仅对单个元素进行操作,因此它仅返回第一个函数的值:

 console.log($('.price').length) console.log($('.price').attr('id')) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="price" id="id1" value="value1"></div> <div class="price" id="id2" value="value2"></div> 

您必须为每个单独的元素调用函数:

function callMe() {
  $('.price').each(function() {
    var id = $(this).attr("id");
    var titleInput = $(this).attr("value");

    $.ajax({
      type: 'POST',
      url: ajax_object.ajaxurl,
      dataType: 'json',
      data: {
        action: 'myaction',
        post_title: titleInput
      },
      success: function(response) {
        $('#' + id).html(response);
      }
    });
  });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM