2016-05-12 2 views
1

私を困らせる疑問があります、pls助けてください! jqueryのajaxを使ってphp apiを呼び出します。 すぐに結果をajaxに送信する方法

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にしたいが、私のコードは動作しません:

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

PHPコードは、中/スター/マーク方式を推奨します。

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スクリプトが実行を終了するのを待つでしょう。

REF:continue processing php after sending http response

+0

ウェブサーバは 'Connection'ヘッダを削除したり変更したりすることがあります。この場合、vHost config(またはapacheが使用されている場合はhtaccess)ではなく、ヘッダーを設定する必要があります。 –

0

ます。またflush()後にこの2つの関数を呼び出す必要があります:

session_write_close(); 
fastcgi_finish_request(); 
関連する問題