通过jquery/ajax和json抛出php异常的干净方法 [英] Clean way to throw php exception through jquery/ajax and json

查看:54
本文介绍了通过jquery/ajax和json抛出php异常的干净方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种干净,简单的方法来通过json响应jquery/ajax调用引发php异常.

Is there a clean, easy way to throw php exceptions through a json response jquery/ajax call.

推荐答案

您可以在PHP中执行类似的操作(假设通过AJAX调用此方法):

You could do something like this in PHP (assuming this gets called via 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(),
        ),
    ));
}

在JavaScript中:

In JavaScript:

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

您还可以通过返回400(例如)标头来触发$ .ajax()的error:处理程序:

You can also trigger the error: handler of $.ajax() by returning a 400 (for example) header:

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

或使用Status:(如果您使用的是FastCGI).请注意,error:处理程序不会收到错误详细信息;要完成此操作,您必须重写$.ajax()的工作方式:)

Or use Status: if you're on FastCGI. Note that the error: handler doesn't receive the error details; to accomplish that you have to override how $.ajax() works :)

这篇关于通过jquery/ajax和json抛出php异常的干净方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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