2012-10-02 10 views

risposta

44

Si potrebbe fare qualcosa di simile in PHP (supponendo che questo viene chiamata tramite la tecnologia AJAX):

<?php 

try { 
    if (some_bad_condition) { 
     throw new Exception('Test error', 123); 
    } 
    echo json_encode(array(
     'result' => 'vanilla!', 
    )); 
} catch (Exception $e) { 
    echo json_encode(array(
     'error' => array(
      'msg' => $e->getMessage(), 
      'code' => $e->getCode(), 
     ), 
    )); 
} 

In JavaScript:

$.ajax({ 
    // ... 
    success: function(data) { 
     if (data.error) { 
      // handle the error 
      throw data.error.msg; 
     } 
     alert(data.result); 
    } 
}); 

Si può anche innescare il error: gestore di $ .ajax () restituendo un intestazione 400 (ad esempio):

header('HTTP/1.0 400 Bad error'); 

Oppure utilizzare Status: se sei su FastCGI. Si noti che il gestore error: non riceve i dettagli dell'errore; per realizzare questo bisogna ignorare come $.ajax() funziona :)

+0

Grazie. Esiste comunque la possibilità di attivare la richiamata dell'errore javery ajax? – madphp

+0

@madphp Sì, basta restituire il codice http 400 utilizzando l'intestazione() –

+0

E per PHP> = 5.4 è possibile utilizzare 'http_response_code (400);' – PhoneixS

6

Facebook fare qualcosa nel loro SDK PHP dove gettano un'eccezione se una richiesta HTTP non riuscito per qualsiasi motivo. Si potrebbe prendere questo approccio, e solo restituire l'errore e eccezione dettagli se viene generata un'eccezione:

<?php 

header('Content-Type: application/json'); 

try { 
    // something; result successful 
    echo json_encode(array(
     'results' => $results 
    )); 
} 
catch (Exception $e) { 
    echo json_encode(array(
     'error' => array(
      'code' => $e->getCode(), 
      'message' => $e->getMessage() 
     ) 
    )); 
} 

È quindi possibile solo ascoltare per la chiave error nel vostro AJAX chiamate in JavaScript:

<script> 
    $.getJSON('http://example.com/some_endpoint.php', function(response) { 
     if (response.error) { 
      // an error occurred 
     } 
     else { 
      $.each(response.results, function(i, result) { 
       // do something with each result 
      }); 
     } 
    }); 
</script> 
4

Se tutti gli errori devono essere trattati allo stesso modo (mostrando una finestra di dialogo per esempio). Si può fare in questo modo:

PHP fine:

public function throwJsonException($msg) { 
    echo json_encode(array('error'=> true, 'msg' => $msg)); 
} 

throwJsonException('login invalid!'); 

jQuery fine:

$(document).ajaxSuccess(function(evt, request, settings){ 
    var data=request.responseText; 
    if (data.length>0) { 
     var resp=$.parseJSON(data); 
     if (resp.error) 
     { 
      showDialog(resp.msg); 
      return; 
     }     
    }  
}); 
0

Come complemento alle risposte precedenti, invece di ripetere lo stesso codice per la codifica JSON in tutte le eccezioni, è possibile impostare un gestore di eccezioni da utilizzare solo negli script necessari. Per esempio:

function ajaxExceptionHandler($e) { 
    echo json_encode(array(
     'error' => array(
     'code' => $e->getCode(), 
     'msg' => $e->getMessage()) 
    )); 
} 

Poi, nel vostro gestore ajax,

set_exception_handler('ajaxExceptionHandler'); 
Problemi correlati