簡體   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