Jquery bind to link, execute some post jquery then load link
is there a clean way to bind a jquery post on a link and after the post is executed to load the link as it should do normally ?
here is my code:
$("a").bind('click', function(e){
// disable click while we make a post request
e.preventDefault();
// make post request
$.post('/blablabla/', { "datas" : mydatas } );
});
for now i disable click to allow my script to make a POST, but I want the link开发者_开发技巧 bring to the target page after my POST is called and successfully executed. I think I need a callback but cannot find a good way to achieve it.
Thanks by advance,
Add a success function to your .post
call which changes window.location
to the href
of the clicked link.
$( 'a' ).bind( 'click', function( e )
{
var url;
# disable click while we make a post request
e.preventDefault();
# get the url from the href attr
url = = $( this ).attr( 'href' );
# make post request
$.post(
'/blablabla/',
{
datas: mydatas
},
function()
{
# send browser to url
window.location = url;
}
);
} );
If you want the redirect to take place even if the POST fails, you could switch to using .ajax()
and use the complete
option:
$( 'a' ).bind( 'click', function( e )
{
var url;
# disable click while we make a post request
e.preventDefault();
# get the url from the href attr
url = = $( this ).attr( 'href' );
# make post request
$.ajax( {
url: '/blablabla/',
type: 'POST',
data: {
datas: mydatas
},
complete: function()
{
# send browser to url
window.location = url;
}
);
} );
$("a").bind('click', function(e){
# disable click while we make a post request
e.preventDefault();
# Save the link url
var url = $(this).attr('href');
# make post request
$.post('/blablabla/', { "datas" : mydatas }, function() {
# Post successful
document.location(url);
} );
});
You should prevent "double clicks" somehow.
You can redirect to the url's href after the $.post
returns.
$("a").bind('click', function(e){
# disable click while we make a post request
e.preventDefault();
var url = $(this).attr('href');
# make post request
$.post('/blablabla/', { "datas" : mydatas }, function(){
window.location = url;
});
});
精彩评论