I have a js widget which is embedded in random sites.
When a user clicks a link I want to report it to my server.
To call my server I create a tag dynamically with src containing the parames reported to the server.
If I do it on onclick event and return true from the onclick, the server probably will not get the call because the browser changes the page (is this correct?).
If I do it on onclick and return false then use redirect af开发者_C百科ter the call to the server is returned, I lose the back button functionality because browsers like IE do not support the back button after redirect.
Any idea of how to do this in a robust way?
There is no problem. If you add an onclick handler to the <a>
elements that sends an AJAX POST to the server (registering the click), this will arrive at the server, the page will still move on to the clicked link, and the back button will work as expected.
Example in jQuery:
$('a').live('click', function () {
$.post('/registerclick/', { data: $(this).attr('src') }, function () {});
});
The reason this works, is because the client/server model in HTML specifies that when a request is sent to the server, it cannot be cancelled. Therefore the following applies:
- Event handler goes off, and a request to the server is sent
- User gets redirected by default browser behavior to the page in the
href
attribute - Server gets the request, even tho the user is at a whole different page
The browser isn't aware of the 3rd step; but that doesn't matter for the server.
精彩评论