2013-07-18 4 views
0

데이터를 PHP 파일로 보내고 다운로드해야합니다.데이터를 PHP로 보내고 파일을 다운로드하십시오.

직접 호출하면 스크립트가 올바르게 작동하지만 AJAX로 데이터를 보낼 때 스크립트가 전혀 다운로드되지 않습니다.

내 질문은 : 어떻게 데이터를 PHP 파일로 보내고 자동으로 파일을 다운로드 할 수 있습니까? 물론 같은 페이지에 머물러 있을까요? 직접 호출 할 때 작동되는 코드의

부 ...

PHP 파일

header('Content-Description: File Transfer'); 
header("Content-type: application/ms-word"); 
header("Content-Disposition: attachment;Filename=ponuda.doc"); 

$productsArr = json_decode($_POST['object']); 
$html = "<tr>"; 
foreach($productsArr as $product) 
{ 
    //something 
} 
.... 
echo $html; 

AJAX 호출 : 나는 다음을 수행

$.ajax({ 
      type: "POST", 
      url: "test_download.php", 
      data: { object:productsJSON }, 
      cache: false 
     }); 
+0

당신은 다운로드 페이지로 리디렉션해야합니다. .exe 링크를 클릭하는 것과 같습니다. 브라우저는 흰색 페이지가 아닙니다. 단순히 통계 만 다운로드하면됩니다. Ajax는 파일 다운로드를 위해 작동하지 않습니다. 불가능합니다. – skrilled

+0

몇 가지 예가 있습니까? –

+1

이 링크를 통해 이동할 수 있습니다. http://stackoverflow.com/questions/11477052/php-file-download-using-hidden-iframe-without-saving?rq=1 – Kasma

답변

0

:

  1. 페이지로드의 기 개체를 초기화 머리 부분에 자바 스크립트 파일 exchanger.js 포함 : theBuffer = new exchanger('dwnld');
  2. 당신이 파일 다운로드 시작 할 때마다 호출하는 자바 스크립트 함수 만들기 :

    function downloadFile(){ 
         // you can add parameters to the function as needed to pass in dynamic data sent to the back end download handler 
         data = "http://your_backend_file_download_handler.php?param1=val1&param2=val2&etc=whatever"; // send whatever data you need to the php program via query string parameters 
         theBuffer.sendData(data); // initiate the file download 
    } 
    

    참고 : 요청을 처리하는 PHP 백엔드 파일 다운로드 프로그램은 올바른 데이터/파일을 다운로드/다운로드하기 위해 보내는 매개 변수와 관련된 모든 작업을 수행 할 수 있습니다. 많이 고친 후 this combination은 일관되게 나를 위해 일하는 무엇입니까

  3. 당신의 신체 섹션에 html의이 작은 비트를 포함하십시오. 나는 보통 BODY 태그를 닫기 바로 전에 넣어 :

    <iframe name="dwnld" id="dwnld" style="width:0;height:0;border:0"> 
    </iframe> 
    
    Note: the id value assigned to the iframe is the same value given in step 2 when initializing. 
    

결과는 실제 다운로드가 별도의 페이지에서 처리되기 때문에 사용자가 결코 파일의 수를 다운로드 현재 페이지를 잎 없다는 것입니다 (일명 iframe). 나는 수년간 나의 모든 프로젝트에서이 문제없이 사용 해왔다.

0

나는 당신이 아약스에 의해 브라우저에 헤더를 보낼 수 없다고 생각하지만, 당신은 이것을 사용할 수있다. 헤더가 올바르게 설정하고 브라우저가가, 다음이 작동 파일을 다운로드하는 대신 페이지를 표시하는 것 인식하는 경우

http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/

$.fileDownload('file.mp3') 
    .done(function() { alert('File download a success!'); }) 
    .fail(function() { alert('File download failed!'); }); 
관련 문제