繁体   English   中英

如何使用href调用函数?

[英]How can I call a Function with a href?

我正在尝试将一个函数调用到href ,我的functionfunctions.php而我的hrefviews/something.php

因此,这是我的功能:

function discount($connection, $us){
    $discount = $conexion->prepare("UPDATE postule SET seen = 1 WHERE id = $us");
    $discount->execute();
    return $discount;
}

而我的link button<li> (不是形式):

<?php foreach ($total_notu as $notu) : ?>
    <li><a onClick="<?php discount() ?>" href="notificaciones.php"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
  <?php endforeach; ?>

(不要注意foreach)

您需要更改它以使用ajax调用或表单发布来调用PHP函数。

这是一个非常基本的示例,应该为您指明正确的方向

Discount.php

<?php

    // Load $connection from somewhere

    // Get user, it's better to get this from a cookie or session rather than GET
    $user = $_GET['user']

    $discount = $connection->prepare("UPDATE postule SET seen = 1 WHERE id = :user");
    $discount->bindParam(':user', $user);
    $result = $discount->execute();

    // Throw error if something went wrong with the update, this will cause $.ajax to use the error function
    if (!$result) {
        http_response_code(500);
    }

html,假设$notu[0]包含用户ID

<?php foreach ($total_notu as $notu) : ?>
    <li><a onClick="return callDiscount('<?php echo "$notu[0]"; ?>');" href="#"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
<?php endforeach; ?>

js,需要jquery

function callDiscount(user_id)
{
    // Perform ajax call to discount.php
    $.ajax({
        url: '/discount.php?user=' + user_id, 
        error: function() {
            alert('An error occurred');
        },
        success: function(data) {
            // Redirect user to notificaciones.php
            document.location = '/notificaciones.php';
        }
    });

    // Prevent link click doing anything
    return false;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM