2016-05-12 62 views
1

有一個問題困擾着我,請幫助! 我使用jquery的ajax來調用一個php api。如何將結果立即發送到ajax

$.ajax({ 
      type:"POST", 
      dataType:"json", 
      data:{type:type,fid:fid,model:'star'}, 
      url:'Recommend/Star/mark', 
      success:function (data) { 
       //do something 
      }, 
     ... 
     }); 

PHP代碼中推薦/明星/標記方法:

error_reporting(0); 
    set_time_limit(0); 
    ob_implicit_flush(true); 
    ob_end_clean(); 

    ob_start(); 
    echo json_encode($boolMark); 
    ob_flush(); 
    flush(); 

    sleep(3); 
    $this->afterMark($uid, $fid); 

我想PHP的回聲結果立即AJAX,但我的代碼將不會工作。

如何讓php立即向ajax發送結果,並繼續執行剩餘的代碼?

回答

1
.... 
echo json_encode($boolMark . "<br>\n"); 
// get the size of the output 
$size = ob_get_length(); 
// send headers to tell the browser to close the connection 
header("Content-Length: $size"); 
header('Connection: close'); 
ob_end_flush(); 
ob_flush(); 
flush(); 
/******** background process starts here ********/ 

ignore_user_abort(true); 

/******** background process ********/ 
set_time_limit(0); //no time limit 

/******** Rest of your code starts here ********/ 
+0

我面前回答了幾分鐘,你佐丹奴利瑪竇回答一樣,好奇:)。 – hamboy75

+0

謝謝你的回答,它可以幫助我很多! :-) – grey256

0

基本上,你希望你的代碼在「背景」,發送響應後運行,這樣做,你需要這樣的:

// Destroy the current buffer (Just in case...) 
ob_clean(); 
// Start a new buffer 
ob_start(); 

// Send your response. 
echo json_encode($boolMark); 

// Disable compression (in case content length is compressed). 
header("Content-Encoding: none"); 

// Set the content length of the response. 
header("Content-Length: ".ob_get_length()); 

// Close the connection. 
header("Connection: close"); 

// Flush all output. 
ob_end_flush(); 
ob_flush(); 
flush(); 

這將發送完整的報頭和關閉連接,否則你的連接將保持活動狀態,您的瀏覽器將等待php腳本終止其執行。

裁判:continue processing php after sending http response

+0

網絡服務器可能會刪除或更改「連接」標題。如果是這種情況,應該在vHost配置中(或者如果使用apache,則爲htaccess)設置標題。 –

0

您還需要flush()之後調用這兩個函數:

session_write_close(); 
fastcgi_finish_request();