我在這里可能沒有使用正確的方法,但我有一個 ErrorHandler 類,它會在出現錯誤時輸出錯誤頁面,如下所示:private function loadErrorPage() { if( file_exists( $this->errorPagePath ) ) { // load the error page: since it's an include, it'll have access all of this classe's properties! // i.e. $this->errstr, $this->errid, etc. include ( $this->errorPagePath ); } // no error page! print generic message! else { echo 'Got a problem! Contact the admin!'; } exit(); }我遇到的問題是有時我的頁面是通過 AJAX 調用來調用的!如果我的 POST 中有錯誤被錯誤處理程序捕獲,我需要能夠 exit(),在 JSON 響應中返回完整生成的頁面,或者只是指向它的鏈接,在 JS 中,重定向到實際的$this->errorPagePath頁面回復中給出。但是,后面的解決方案不太有效,因為它需要所有必需的錯誤處理程序屬性,例如 errid、錯誤字符串等。不知道如何繼續這里。有沒有辦法可以將 include() 的結果輸出到變量中并執行以下操作:$generatedErrorPage = include ( $this->errorPagePath );if ( $this->sendErrorPageInJSON ) { exit(json_encode([ 'errorHtml' => $generatedErrorPage ]));}else{ echo $generatedErrorPage; exit();}
1 回答

紅糖糍粑
TA貢獻1815條經驗 獲得超6個贊
您必須啟動輸出緩沖,包括文件并結束緩沖以使用其內容初始化變量
// Start output buffering
ob_start();
// Include the file
include ( $this->errorPagePath );
// End buffering and return its contents
$generatedErrorPage = ob_get_clean();
- 1 回答
- 0 關注
- 135 瀏覽
添加回答
舉報
0/150
提交
取消