2016-08-26 7 views
2
public function jsonExit($array) 
{ 
    $this->con->output->set_content_type('application/json'); // $this->con is get_instance from the constructor 
    echo json_encode($array); 
} 

このコードは、JSON形式でデータを正しく出力します。しかし、関数にexit;を含めると、定義したapplication/jsonの代わりにtext/htmlになります。CodeIgniter出力でExitを使用すると、コンテンツタイプヘッダがtext/htmlになります。

理由は何ですか?そして私はexitを置き換えることができますか?この場合、returnはこの機能の実行を停止するだけで機能しませんjsonExitしかし、私はjsonExit関数と呼ばれる場所からスクリプトを実行し続けます。私の仕事は完全に終了することです。

+1

に使用されているよう( 'ダイを試してみてください);'、それはあなたが望むものである場合には、スクリプトの実行を停止する必要があります。 – coderodour

+0

なぜあなたは 'exit'をインクルードしますか? jsonExitは、それを終了させたいときに 'false'を返すことができます。コントローラまたは何らかの関数が' if(!jsonExit($ array)){die(); } ' – mazedlx

答えて

2

これは直接echoを使用しているためです。

代わりにset_outputを使用してください。 Docs here

public function jsonExit($array) 
{ 
    $this->con->output->set_content_type('application/json'); // $this->con is get_instance from the constructor 
    $this->con->output->set_output(json_encode($array)); 
} 

あなたはexitまたはdie使用_displayが必要な場合。 Docs here

このメソッドは、スクリプトの実行の終了時に自動的に呼び出され、あなたのコード内で)(あなたが終了を使用してスクリプトの実行を中止されていない限り、(手動で呼び出す必要があります)または死ぬことはないだろう。

public function jsonExit($array) 
{ 
    $this->con->output->set_content_type('application/json'); // $this->con is get_instance from the constructor 
    $this->con->output->_display(json_encode($array)); 
    exit(0); 
} 

か、example

関連する問題