我希望通过ajax从codeigniter中的foreach循环中获取特定的图像ID

时间:2016-12-09 17:23:18

标签: ajax codeigniter foreach-loop-container

我想从foreach循环获取图像的特定记录,然后我想将此值带到另一页

<?php foreach($portfolio_image as $image):?>
    <h3><?=$image->portfolio_image_title?></h3>
    <p><?=$image->portfolio_image_detail?></p>
    <a id="lin" href="#portfolio-si" data-id="<?=$image->portfolio_image_id?>">
<?php endforeach;?>

<script>
         $(document).ready(function(){
             $('#lin').click(function(evt){
               evt.preventDefault()
                   $.ajax({
                       type : 'POST',
                       url  : "<?=base_url();?>index.php/home/single_portf",
                       data : {id:$('#lin').attr('data-id')},
                       cache : false,
                       success: function(data){
                           $('#portfolio-sig').html(data);
                       }
                    });
      });
</script>

1 个答案:

答案 0 :(得分:0)

您可以使用class="lin",如下所示:

<a id="lin" class="lin" href="#portfolio-si" data-id="<?=$image->portfolio_image_id?>">

更改jquery onclick函数,如下:

$('.lin').click(function(evt){

然后使用类似下面的jquery $(this)方法:

data : {id:$(this).attr('data-id')},

所以,最后:

<?php foreach($portfolio_image as $image):?>
    <h3><?=$image->portfolio_image_title?></h3>
    <p><?=$image->portfolio_image_detail?></p>
    <a id="lin" class="lin" href="#portfolio-si" data-id="<?=$image->portfolio_image_id?>">
<?php endforeach;?>

<script>
$(document).ready(function(){
    $('.lin').click(function(evt){
        evt.preventDefault();
        var id = $(this).attr('data-id');

        $.ajax({
           type : 'POST',
           url  : "<?=base_url();?>index.php/home/single_portf",
           data : {id: id},
           cache : false,
           success: function(data){
               $('#portfolio-sig').html(data);
           }
        });
    });
});
</script>