firing href link for download and .click event with $.post() with jquery
im trying to have one link for a file download and at the same time submit a post form over ajax. kinda looks like this:
<form action="" method="post" id="form">
<input type="text" name="email" id="email" value="" />
<input type="hidden" name="subscriber" id="subscriber" value="newsletter" />
<a href="/files/application.exe" id="download">trial download</a>
</form>
<script type="text/javascript" src="jquery"></script>
<script type="text/javascript">
// prevent default submit action caused by enter key etc.
$("#form").bind('submit',function(event){event.preventDefault();});
$('#download').click(function(){
$.post(location.href, $('#form').serialize(), function(){
$('#form').hide();
});
});
</script>
problem is that the download fires and it shows the download dialog - which is correct - it also fires the click event and would even console log inside the click event function, it on top even fires the post request but the post request never 开发者_如何学Pythonends up at the server. i had the access log file on tail -f and it only shows the GET on the application.exe but no POST from the $.post(). in firebug it shows the POST http://ip/folder/ given by the location.href and its marked in red with a little X and an empty response field. tough for firebug it looks like it got sent to the server...
my explanation for this is that the href takes the wind out of the $.post() and before it gets fired it redirects the browser to the download file. doesnt change the page itself but stops the action of posting over XHR...
does anyone know a good workaround for this? i really need the native href link to the application to not cause IE to bring up this stupid file download warning bar and at the same time i need the ajax to submit the form...
thanks!
Refactor as follows, returning false
to prevent the default link click behavior:
$('#download').click(function(){
var href = $(this).attr('href');
$.post(location.href, $('#form').serialize(), function(){
$('#form').hide();
document.location.href= href;
});
return false;
});
to give one answer that works to my own question:
$('#download').click(function(){
setTimeout(function(){
$.post(location.href, $('#form').serialize(), function(){
$('#form').hide();
});
},1000);
});
the timeout fires the .post after the download request is fired... sortof works... but i dont know if thats a good solution or if that might fail 50% of the time & browser...
精彩评论