代码之家  ›  专栏  ›  技术社区  ›  botmsh

用jquery处理PHP异常

  •  2
  • botmsh  · 技术社区  · 16 年前

    我正在使用jquery调用一个PHP函数,该函数在成功时返回一个JSON字符串或抛出一些异常。我正在打电话 jQuery.parseJSON() 在响应上,如果失败,我假设响应包含异常字符串。

    $.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
                }
    

    有人能建议一种更优雅的方法来捕获异常吗?

    多谢, 伊塔玛

    4 回复  |  直到 16 年前
        1
  •  2
  •   Jacob Relkin    16 年前

    好吧,在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
                }
    
        2
  •  3
  •   Pekka    16 年前

    在PHP脚本中捕获异常-使用 try .... catch 块-当发生异常时,让脚本输出带有错误消息的JSON对象:

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

    然后,您将在jquery脚本中查找错误消息,并可能将其输出。

    另一种选择是发送 500 internal server error 当PHP遇到异常时的头:

    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对象将调用错误回调函数,并在其中进行错误处理。

        3
  •  0
  •   Ionuț G. Stan    16 年前

    在PHP端捕获异常,并以JSON格式输出错误消息:

    echo json_encode(array(
        'error' => $e->getMessage(),
    ));
    
        4
  •  -1
  •   Tolga Evcimen    10 年前
    echo json_encode(array(
        'error' => $e->getMessage(),
    ));
    
    推荐文章