如何在PHP中获取HTML按钮的data-value =“1”?

时间:2017-08-17 21:03:06

标签: javascript php jquery html twitter-bootstrap

我用data-value="1"属性覆盖Bootstrap模态按钮的值,以便在我的PHP中使用它。但是我的PHP代码正在返回null。值是要在数据库中检入的ID:

if (value matches) {
    do this
} else {
    do this
}

这是我的代码:

HTML

<button type="button" class="btn btn-primary"  id="bookNow" data-value='1' data-toggle="modal" data-target="#myModal">Book Now</button>

引导模式

<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Confirm Booking</h4>
            </div>
            <div class="modal-body">
                <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                    <button type="submit" class="btn btn-primary" name="bookMe" value=""  id='btnCon' data-value="" >Confirm</button>
                    <input type="submit" class="btn btn-danger" name="reset" value="Cancle" data-dismiss="modal">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

的Javascript

<script type="text/javascript">
    //value getter
    var btn = document.getElementById('bookNow');
    var modalBtn = document.getElementById('btnCon');
    //evnt liestenr
    btn.addEventListener('click', handleClick);
    modalBtn.addEventListener('click',handleModal);
    //event Functions
    function handleClick (e) {
        var btn = e.target;
        var value = btn.dataset.value;
        var modalBtn = document.getElementById('btnCon');
        modalBtn.dataset.value = value;
    }
    function handleModal (e) {
        var btn = e.target;
        var value = btn.dataset.value;
        console.log(value);
    }
</script>

PHP

if (isset($_POST['bookMe'] == null)){
    echo "data-value is null";
}

1 个答案:

答案 0 :(得分:1)

data-value并未自动发送到服务器,但您可以使用AJAX完成此操作。我建议你在表单中使用隐藏的输入,并将值设置为你需要的值:

<input type="hidden" name="bookMe" value="whateverValue" />