Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

javascript - JQuery: Perform a post before a link is followed

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. I think the problem is that it is following the link before something can happen. I don't actually need to wait for the response back from the server, I just need it to send the call to it. Can anyone help me out? Maybe how to delay following the link before it is called or should I be note using $.post?

$("#item").click(function (ev) {
    $.post(link_to_something);
});

<a id="item" href="www.google.com">Link</a>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...