JQuery: Perform a post before a link is followed

后端 未结 2 897
醉酒成梦
醉酒成梦 2021-01-21 22:46

I need to do an asynchronous post to a server when someone on my site clicks a link. I tried the code below, but it doesn\'t seem to be doing the task on the server I want it to

相关标签:
2条回答
  • 2021-01-21 23:07

    The first thing is to cancel the default action of the link by returning false from the click handler. This will allow enough time for the AJAX request to complete. And when it completes, inside the success callback you could redirect to wherever the link is pointing to:

    $("#item").click(function (ev) {
        var self = this;
        $.post(link_to_something, function() {
            window.location.href = self.href;
        });
        return false;
    });
    
    0 讨论(0)
  • 2021-01-21 23:23

    You have to check the response to determine whether the post has been succeeded or not then you should go on.

    $("#item").click(function (e) {
        e.preventDefault();
        $.post(link_to_something, function() {
            window.location = $(this).attr('href');
        });
    });
    
    0 讨论(0)
提交回复
热议问题