2010-05-11 100 views
2

我正在使用JQuery調用成功返回JSON字符串的PHP函數,或者引發一些異常。目前,我在響應中調用jQuery.parseJSON(),如果失敗,我假設響應包含一個異常字符串。使用JQuery處理PHP異常

 
$.ajax({ 
      type: "POST", 
      url: "something.php", 
      success: function(response){ 
       try { 
        var json = jQuery.parseJSON(response); 
       } 
       catch (e) { 
        alert(response); 
        return -1; 
       } 
       // ... do stuff with json 
      } 

任何人都可以提出一個更優雅的方式來捕捉異常?

非常感謝, 伊塔馬爾

回答

2

好了,你可以在PHP中的全局異常處理程序,它會調用json_encode它然後回顯出來。

<?php 
    function handleException($e) { 
     echo json_encode($e); 
    } 
    set_exception_handler('handleException'); 
?> 

然後,您可以檢查是否json.Exception != undefined

$.ajax({ 
      type: "POST", 
      url: "something.php", 
      success: function(response){ 
       var json = jQuery.parseJSON(response); 
       if(json.Exception != undefined) { 
        //handle exception... 
       } 
       // ... do stuff with json 
      } 
0

捕捉JSON格式在PHP端以外,並輸出一個錯誤消息:

echo json_encode(array(
    'error' => $e->getMessage(), 
)); 
3

捕捉異常在PHP腳本 - 使用try .... catch塊 - 並且在發生異常時,有腳本輸出一個JSON對象,並顯示一條錯誤消息:

try 
    { 
    // do what you have to do 
    } 
catch (Exception $e) 
    { 
    echo json_encode("error" => "Exception occurred: ".$e->getMessage()); 
    } 

你再看看這條錯誤消息在您的jQuery腳本,並可能將其輸出。

另一種選擇是PHP遇到異常時發送一個500 internal server error標題:然後

try 
    { 
    // do what you have to do 
    } 
catch (Exception $e) 
    { 
    header("HTTP/1.1 500 Internal Server Error"); 
    echo "Exception occurred: ".$e->getMessage(); // the response body 
                // to parse in Ajax 
    die(); 
    } 

您的Ajax對象將調用錯誤回調函數,你會做在那裏處理您的錯誤。

+0

非常有用!我有與jQuery Ajax相同的問題(該庫沒有捕獲我從PHP中拋出的異常)。使用500 Http代碼發送標題已解決了我的問題。謝謝 – 2012-08-23 15:49:19

-1
echo json_encode(array(
    'error' => $e->getMessage(), 
));