从Jquery访问php值


Access php value from Jquery

很奇怪,我在Google上什么也没找到,但我希望你能帮助我。我有一张不同账户的表。当我单击其中一行时,这个特定帐户的另一个表将滑动进来。这个帐户的"特定表"需要显示一些帐户指定的数据,因此我需要告诉我的ajax请求他需要这些数据的帐户。问题是:我不知道该如何判断。我从来没有使用过没有表单的Ajax请求。

我的HTML表(我需要var $orderid为我的ajax请求)

foreach($data as $row)
{
    $orderid =$row['id'];
    $username = $row['name'];
    $done = $row['refsDone'];
    $quantity = $row['quantity'];
    $running =$row['refsRunning'];
    $untouched = $quantity - ($done+$running);
    echo "
        <tr class='header mySlideToggler'>
        <td class='align-center'>$username</td>
        <td>0 %</td>
        <td>22 Aug 2014</td>
        <td>$done / $quantity</td>
        <td>$running</td>
        <td>$untouched</td>
        <td>
            <a href='#' class='table-icon edit' title='Edit'></a>
            <a href='#' class='table-icon expand mySlideToggler' title='Expand'></a>
            <a href='#' class='table-icon delete' title='Delete'></a>
        </td>
        </tr><tr style='padding: 0'><td colspan='7' style='padding: 0'>
            <div class='slideMe' style='display: none'>
                Content of the additional info is here
            </div>
        </td></tr>";
}

我的Jquery部分,它只处理div的滑动效果和它的触发函数:

$('.mySlideToggler').click(function( event ){
    event.preventDefault();
    event.stopPropagation();
    $(this).closest('tr').next().find('.slideMe').slideToggle();
});

所以基本上我的问题是:我怎么能访问php值$orderid从我的Jquery函数?

将订单id放入html:

<tr class='header mySlideToggler' data-id="<?php echo $orderid; ?>">

然后:

$('.mySlideToggler').click(function( event ){
  event.preventDefault();
  event.stopPropagation();
  var id = $(this).data('id');
  $(this).next().find('.slideMe').slideToggle();
});

将id存储在JS可以访问的数据属性中

创建一个隐藏变量,并为它赋值$orderid

然后读取jQuery中的相同变量。完成了

您可以在HTML元素中的任何位置设置ordered属性,如下所示:

<?php
foreach($data as $row)
{
    $orderid =$row['id'];
    $username = $row['name'];
    $done = $row['refsDone'];
    $quantity = $row['quantity'];
    $running =$row['refsRunning'];
    $untouched = $quantity - ($done+$running);
 ?>
    <tr class='header mySlideToggler' orderedid='<?php echo $orderedid ?>'>
    <td class='align-center'><?php echo $username ?></td>
    <td>0 %</td>
    <td>22 Aug 2014</td>
    <td><?php echo $done / $quantity ?></td>
    <td><?php echo $running ?></td>
    <td><?php echo $untouched ?></td>
    <td>
        <a href='#' class='table-icon edit' title='Edit'></a>
        <a href='#' class='table-icon expand mySlideToggler' title='Expand'></a>
        <a href='#' class='table-icon delete' title='Delete'></a>
    </td>
    </tr><tr style='padding: 0'><td colspan='7' style='padding: 0'>
        <div class='slideMe' style='display: none'>
            Content of the additional info is here
        </div>
    </td></tr>
<?php 
}
?>

PHP会像简单的HTML属性一样为您呈现正确的id。之后,您可以使用.click()函数中的jQuery选择器访问元素的属性:

$(this).attr('orderedid');

作为一个好的实践,不要"回显"你的HTML。取而代之的是,在PHP标记中包含纯HTML。