如何使用href调用函数? [英] How can I call a Function with a href?

查看:737
本文介绍了如何使用href调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I´m trying to call a function into a href, my function is on functions.php and my href is on views/something.php

所以,这是我的功能:

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

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

and my link button is on an <li> (not in a form):

<?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)

(Do not pay attention to the foreach)

推荐答案

您需要将其更改为使用ajax调用或表单发布来调用PHP函数.

You'll need to change this to use an ajax call or form post to call the PHP function.

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

Here's a really basic example which should point you in the right direction

discount.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

html, assuming $notu[0] contains the user 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;
}

这篇关于如何使用href调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆