在PHP CodeIgniter中获取jquery正在加载的数据


Get the data that is being loaded by jquery in PHP CodeIgniter

我在CodeIgniter:中使用form_helper有这个下拉菜单

  <?php if($materialType): ?>
    <?php 
    $material_options = array();
    foreach($materialType as $rows){
        $material_options[$rows->id] = $rows->category; 
    }                                       
    echo form_dropdown('materialType',$material_options,'','id="materialType"');
    ?>
<?php endif; ?>
  <div id="materials"></div>

上面的代码在<form>标签中,我有这样的脚本:

  <script type="text/javascript">
    var base_url = "<?php echo base_url(); ?>"; 
  </script>
  <script> 
    $(document).ready(function(){
        $(document).on('change','#materialType',function(){
                loadthis();                 
            });
            function loadthis(){
                var ID  = $('#materialType').val();
                var dataString = 'id='+ ID ;
            $.ajax({
                type: "POST",
                url: base_url + "index.php/admin/get_material",
                data: dataString,
                cache: false,
                success: function(data)
                    {
                    $('#materials').html(data);
                    }
                });     
            }
            loadthis();
        });
 </script>

这是正在加载的代码:

   <div id="materials">
   <?php if($materials): ?>
        <table>
            <th>Name</th>
            <th>Description</th>
            <?php foreach($materials as $row): ?>
            <tr>
                <td><?php echo $row->mname; ?></td>
                <td><?php echo $row->mdesc; ?></td>
                <td>
                    <button class="try" value="<?php echo $row->id; ?>">Add</button>
                </td>
            </tr>
    <?php endforeach; ?>
    </table>
<?php else: ?>
    <div class="alert alert-error" style="width:300px;">No Resource Available!</div>
<?php endif; ?>

   $(document).on('click','.try',function(){
            alert($(this).val());
            return false;
        });

我想要的是,如果Add button被点击,我可以获得IDmname并将其存储,直到表单提交
如何在jquery中使用.data()?或者在提交表单之前如何存储它的任何想法。

我没有仔细研究您的代码,但我注意到,当您在循环中打印表行时,所有行都分配了id="try"。html id-属性是一个唯一的标识符,因此提醒该值的JS将只返回它将找到的第一个id的值(至少我是这么认为的)。尝试使用class代替id,然后在js中使用this

$(document).on('click','.try',function(){
    alert($(this).val());
    return false;
});