views:

65

answers:

2

Is it possible to a jquery $.get() to call a servlet and use it to both download a file or update the page without reloading the page? (Or more basically, can I download a file without reloading the page?)

For example, I am using a servlet that either returns a file to download of mimetype "application/octet-stream", or returns text to be update in the page of type "text/html".

I can write a form with a submit, but then it reloads the page, so I've been trying to use $.get()... but the download doesn't work.

<script type="text/javascript">
 jQuery(document).ready(function(){ 
   $("#handleFileOptions button").button();
  });

  function handleFilesSubmit(requestType)
  {
     $.get('FileServlet', {filename: $('#radioFileList input:radio:checked').button("widget").text(), requestType: requestType}, function(data){ ...?... });
   }
</script>

In the html:

<div id = "handleFiles">
 <div id ="radioFileList">
   <div id="radioFileList">
     <input value="file0.txt" type="radio" id="fileitem0><label for="fileitem0">file0.txt</label>
     <input value="file1.txt" type="radio" id="fileitem1><label for="fileitem0">file1.txt</label>
   </div>
 </div>
 <div id="handleFileOptions">
   <button id="handleFileOption0" onclick="handleFilesSubmit('Download')">Download</button>
   <button id="handleFileOption1" onclick="handleFilesSubmit('Delete')">Delete</button>
 </div>
</div>

Solution As per the suggestion below, I changed the submit function to load the servlet directly as:

function handleFilesSubmit(requestType)
{
  if(requestType == "Download"){
     window.location.replace("FileServlet?filename="+$('#radioFileList input:radio:checked').button("widget").text()+"&requestType="+requestType);
  }
  else {     
     $.get('FileServlet', {filename: $('#radioFileList input:radio:checked').button("widget").text(), requestType: requestType}, function(data){ ...?... });
  }
}
+2  A: 

Actually, have you tried just having it load the file to download? Most browsers will detect it is a file, and not navigate away from the page. They will just show the download dialog box.

webdestroya
+1 great suggestion. That is the proper way to handle this.
Byron Whitlock
Thanks - I added a function for download that calls window.location.replace(), and that works like a charm.
Adam
A: 

Do the submit in a tiny iframe. Not the prettiest solution but it gets by the issues you are working with.

Byron Whitlock