Handling PHP exceptions with JQuery

前端 未结 4 1193
野性不改
野性不改 2021-01-15 10:08

I\'m using JQuery to call a PHP function that returns a JSON string upon success or throws some exceptions. Currently I\'m calling jQuery.parseJSON() on the res

4条回答
  •  梦谈多话
    2021-01-15 11:00

    Catch the exception in your PHP script - using a try .... catch block - and when an exception occurs, have the script output a JSON object with an error message:

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

    you would then look for the error message in your jQuery script, and possibly output it.

    Another option would be to send a 500 internal server error header when PHP encounters an exception:

    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();
      }
    

    your Ajax object will then invoke the error callback function, and you would do your error handling in there.

提交回复
热议问题