使用JQuery处理PHP异常 [英] Handling PHP exceptions with JQuery

查看:100
本文介绍了使用JQuery处理PHP异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JQuery调用一个PHP函数,成功返回一个JSON字符串或抛出一些异常。目前,我在响应中调用 jQuery.parseJSON(),如果失败,我认为响应包含一个异常字符串。


$ b $

$ b $ .ajax({
type:POST,
url:something.php,
success:function(response){
try {
var json = jQuery.parseJSON(response);
}
catch(e){
alert(response);
return -1;
}
// ...做json的东西
}

任何人都可以建议更多非常感谢
Itamar

解决方案



div>

嗯,你可以在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){
//处理异常...
}
// ...做json的东西
}


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 response and if it fails I assume the response contains an exception string.

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

Can anyone suggest a more elegant way to catch the exception?

Many thanks, Itamar

解决方案

Well, you can have a global exception handler in PHP that would call json_encode on it then echo it out.

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

You could then check if, say, 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
            }

这篇关于使用JQuery处理PHP异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆