将值从bootstrap data-id传递给php变量

时间:2014-04-14 01:44:42

标签: php jquery twitter-bootstrap modal-dialog

我有一个带有几个月值的下拉菜单。这是其中一个例子。

<li data-toggle="modal" data-id="January" class="random " href="#AddMonth">January</li>

我想通过&#34; 1月&#34;值变为php变量。像这样的东西

<div class="modal fade" id="AddMonth" 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-hidden="true">&times;</button>
    <h4 class="modal-title" id="myModalLabel">Update your information</h4>
  </div>
  <div class="modal-body">
      <?php
         // $month  = ? // month will contain the variable that was pass from data-id
         MethodSendMonthData($month);

       ?>
  </div>
</div>

我不确定怎么能实现这个目标?

1 个答案:

答案 0 :(得分:1)

先前详细说明我的评论。

您可以使用jQuery.ajax甚至jQuery.post来实现此目标。

例如,您的元素的ID为 mymonth

<li id="mymonth" data-toggle="modal" data-id="January" class="random " href="#AddMonth">January</li>

现在使用jQuery可以获得触发器:

$(document).on('click', 'li#mymonth', function(){
    // get month
    var val = $(this).attr('data-id');

    $.post('myphpfile.php', {month: val}, function(data){
        console.log(data);
    });
});

如您所见,我们抓取属性data-id并将其存储在val变量中。然后将其发布到示例php文件:myphpfile.php

myphpfile.php 会有你的p​​hp功能(当然是示例):

<?php 

if(isset($_POST['month']) && !empty($_POST['month'])) {
    // do your sanatizing and such....
    // do your php stuff
    MethodSendMonthData($month);

   // you can echo back what you need to and use that in jquery as seen above
}

?>