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

巧了我就是萌 提交于 2021-02-10 05:49:30

问题


I have a few products in a mySQL database whose links are being retrieved in my script with $producturl. These url's actually add the product to the cart (http://www.example.com/cart/?add-to-cart=1127). I am trying to create a script that will allow the user to add products to the cart but NOT redirect them, just execute the link so the user stays on the same page.

I am using preventDefault and stopPropgation but it is not working. The alert shows up but the link itself is not executing when I view my cart later the product is not there. Any help?

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

回答1:


Your HTML anchor link:

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

The jQuery JS required (don't forget to put this inside a DOM ready function):

// 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
    });
});

This demonstrates all the principles required to implement your function.

The page in question and the URL POSTed to must be on the same subdomain, or cross origin resource sharing must be appropriately enabled on the server otherwise the request will fail due to cross domain restrictions.




回答2:


Try:

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

or

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



回答3:


You can use an image, a button, a div or a text decorated as link instead of a link.



来源:https://stackoverflow.com/questions/29079539/how-to-click-a-link-that-will-execute-but-not-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!