在php中使用bootstrap模式的Ajax请求

时间:2015-04-05 15:10:39

标签: php jquery ajax twitter-bootstrap

我试图根据某些值在bootstrap模式中显示一些信息。

这是工作流程

1.在带有标题的循环中显示超链接。

2.点击每个超链接时,抓取id值。

3.使用这些id作为参数发出ajax请求,并在bootstrap模型中显示响应。

1. 显示超链接

//display the hyperlinks in a loop
    <?php $i=0;foreach($services as $service) {?>
      <a href="#myModal" data-toggle="modal"  data-id="<?php echo $service->services_id;  ?>" class="btn-block"><?php echo $service->services_title; ?></a>
    <?php $i++;}?>

2. 获取id值并进行ajaxrequest

 $('#myModal').on('show.bs.modal',function(){
            var id=$(this).data('id');
            //undefined
            alert(id);
            //shows loading text
            //it dosent work
    $('.data-modal').html('loading');
    $.ajax({
        type: 'POST',
        url: '../Functions/form_process.php?action=getdetailsbyid',
        data:{id: id},
        success: function(data) {
          $('.data-modal').html(data);
        },
        error:function(err){
            alert("error"+JSON.stringify(err));
        }
         });
        });

问题是无法获取ID值,alert(id)返回undefined$('.data-modal').html('loading')也未显示

模态

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">THIS IS A SAMPLE POPUP 2</h4>
            </div>
            <div class="modal-body">

            <strong>services.</strong>        
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div> 
</div>

1 个答案:

答案 0 :(得分:2)

假设您的foreach输出的链接如下:

 <a href="#myModal" data-toggle="modal" data-id="123" class="btn-block">title</a>
 <a href="#myModal" data-toggle="modal" data-id="1234567" class="btn-block">another title</a>

然后,您可以调用click方法而不是show.bs.modal来使用$(this)

因此您的代码将更改为:

 $('.btn-block').on('click',function(){
    var id = $(this).data('id');
    alert(id);
    $('.modal-body').html('loading');

       $.ajax({
        type: 'POST',
        url: '../Functions/form_process.php?action=getdetailsbyid',
        data:{id: id},
        success: function(data) {
          $('.modal-body').html(data);
        },
        error:function(err){
          alert("error"+JSON.stringify(err));
        }
    });
 });

<强> Here is an Example


否则,您需要在所有输出的链接上使用唯一ID(您可以使用foreach中的计数器执行此操作)