【问题标题】:Increment by one when pressing a button (in Ajax call)按下按钮时加一(在 Ajax 调用中)
【发布时间】:2020-03-03 06:55:02
【问题描述】:

我有一些标记<span class="points-count">0</span>。按下按钮时,我想在 php.ini 中将此值增加一。我如何做到这一点?

【问题讨论】:

标签: php button increment


【解决方案1】:

您可以使用 jQueryjavascript 等来完成此操作,如果您只想在 PHP 中查看此代码

    <?php  

$current_value = 0;
if($_POST['count']){
    $current_value = $_POST['count'];
    $current_value++;} 
?>
<form action="" method="POST">
    <span class="points-count"><?=$current_value?></span>
    <input type="hidden" name="count" value="<?=$current_value?>">
    <button type="submit">Add</button>
</form>

【讨论】:

    【解决方案2】:

    如果您真的想使用 ajax 调用来计算数字,这里是示例:

    counter.php:

    <?php
        $counter = $_GET['current_value'] + 1;       //value is increase here
        echo json_encode(['new_value' => $counter]); //return the value in JSON format
    ?>
    

    您的 HTML 文件:

    <span class="points-count">0</span>
    <button onclick="count()">Increase</button>
    
    <script type="text/javascript">
        function count() {
            $.ajax({
                url     : "counter.php",
                type    : "GET",
                dataType: "json",
                data    : {
                    current_value: $(".points-count").html() //set value here
                },
                success: function(data) {
                    $(".points-count").html(data.new_value); //finally, get the returned value of the php script
                }
            });
        }
    </script>
    

    【讨论】:

      【解决方案3】:

      而不是使用php。 您可以为此使用 jquery 或 javascript。 php 仅用于服务器端渲染。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-31
        • 2019-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-12
        相关资源
        最近更新 更多