I want to achieve the following behavior in a page link.
When clicking the link, I want:
I'm relatively new to jQuery, and here is my first attempt below. I will be grateful to any jQuery guru here to fill in the gaps (and possibly indicate how the snippet could be improved below).
<html> <head>test page</head> <body> <div><a id="hotlink" href="http://www.example.com">Clik and see</a></div> <script type="text/javascript"> $(document).ready(function(){ $('hotlink').click(function(){ //AJAX Post data here ... //follow the link url (i.e. navigate/browse to the link) ... }); }); </script> </body> </html>
, . , ajax . , , , . , , , , . , :
$('#hotlink').click( function () { $.ajax({ async: false, type: "POST", url: "http://myurl.com/mypage.php", data: "param1=value¶m2=value", // ¶m3=value... etc. }); });
.
window.location ajax.
, :
<script type="text/javascript> $(document).ready(function(){ $('hotlink').click(function(){ var link = $(this); $.post(url, {'data': 'value'}, function() { window.location = link.attr('href'); }); return false; }); }); </script>
, , , -, , ajax, , spinner , .
- -
- ajax, , .
, false, , ajax.
:
$('#hotlink').click(function() { $.post(...); return true; });
true .click(function(){...}) . return false, .
.click(function(){...})
return false
, , #hotlink hotlink ( ).
#hotlink
hotlink
, $.post(...) jquery. : http://api.jquery.com/jQuery.post/
$.post(...)
ajax. (, post) - ajax.
ajax
post
$(document).ready(function(){ $('#hotlink').click(function(){ //AJAX Post data here ... $.ajax({ async: false, data: 'can be a string or object, read docs', url: 'http://example.com/whatever.html', type: 'post' }); //follow the link url (i.e. navigate/browse to the link) ... //(it happens naturally by clicking a link, no need for extra code) }); });
, , . , , , .
;)
<script type="text/javascript"> $(document).ready(function(){ $('#hotlink').click(function(event){ //AJAX Post data here }); }); </script>
# . , event.preventDefault().
#
event.preventDefault()
If you do not want to send an AJAX request, I suggest you send synchronous, otherwise you will not be able to determine whether it was successful or not.