gpt4 book ai didi

javascript - 如何使用 href 调用函数?

转载 作者:行者123 更新时间:2023-12-03 04:08:43 25 4
gpt4 key购买 nike

我正在尝试将函数调用到 href ,我的function已开启functions.php和我的href已开启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> (不是以表格形式):

<?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 函数。

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

折扣.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;
}

关于javascript - 如何使用 href 调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44425371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com