如何单击将执行但不重定向的链接

How to click a link that will execute but not redirect.

本文关键字:重定向 链接 执行 何单击 单击      更新时间:2023-09-26

我在mySQL数据库中有几个产品,它们的链接正在我的脚本中使用$producturl检索。这些网址实际上将产品添加到购物车(http://www.example.com/cart/?add-to-cart=1127)。我正在尝试创建一个脚本,允许用户将产品添加到购物车,但不重定向它们,只需执行链接,以便用户保持在同一页面上。

我正在使用 preventDefault 和 stopPropgation,但它不起作用。警报显示,但链接本身未执行,当我稍后查看购物车时,产品不存在。有什么帮助吗?

<?php $producturl = ProductURL::find(array('Product'=>$tube1->Tube1));
if($producturl[0]->URL!=NULL){  
echo '<span id="shop">Add Cart NoRedirect</span>';
}
?>
<script type="text/javascript">
$(document).on('click', '#shop', function (event) {
 $.post( '<?php echo $producturl[0]->URL; ?>' );
event.preventDefault();
event.stopPropagation();
alert('Product has been added to cart');
});
</script>

您的 HTML 锚链接:

<a id='link1' href="http://www.google.com">Link</a>

需要 jQuery JS(不要忘记把它放在 DOM 就绪函数中):

// Act on clicks to a elements
$("#link1").on('click', function(e) {
    // prevent the default action, in this case the following of a link
    e.preventDefault();
    // capture the href attribute of the a element
    var url = $(this).attr('href');
    // perform a get request using ajax to the captured href value
    $.get(url, function() {
        // success
    });
});

这演示了实现函数所需的所有原则。

有问题的页面和 URL POSTed 必须位于同一子域中,或者必须在服务器上适当启用跨域资源共享,否则请求将因跨域限制而失败。

尝试:

'<a href="#" id="shop">Add Cart NoRedirect</a>'

'<a href="javascript: return false;" id="shop">Add Cart NoRedirect</a>'

您可以使用图像、按钮、div 或装饰为链接而不是链接的文本。

'<a href="javascript: void(0);" id="shop">Add Cart NoRedirect</a>'