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

在ajax请求回调中显示php错误

  •  1
  • dakis  · 技术社区  · 6 年前

    在一页中, test.php ,我只需激活错误报告,停用日志记录,然后调用一个函数 test() ,它不存在。如所料,如果运行代码,则会收到错误消息:

    (!) Fatal error: Uncaught Error: Call to undefined function test() in [path-to]/test.php on line 7
    (!) Error: Call to undefined function test() in [path-to]/test.php on line 7
    Call Stack
    # Time    Memory  Function    Location
    1 0.1336  355848  {main}( )   .../test.php:0
    

    现在,在另一页, index.php ,我只有一个名为 testButton . 如果我按下它,就会向页面发送一个ajax请求 测试.php 执行在 index.php索引 我希望看到:

    • 引发的错误 测试.php error ajax请求的回调;
    • 错误显示在屏幕上。

    不幸的是,这些都没有发生。当我按下按钮时:

    • 这个 success 调用ajax请求的回调;
    • 屏幕上不显示错误。

    你能帮我找到问题,还是找出错误?

    谢谢您。


    使用的系统:

    • 菲律宾比索:7.1.1
    • Apache版本:2.2.31
    • ApacheAPI版本:20051115
    • jquery:3.3.1版

    测试.php:

    <?php
    
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    ini_set('log_errors', 0);
    
    $data = test();
    

    index.php文件:

    <!DOCTYPE html>
    <html>
        <head>
            <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
            <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
            <meta charset="UTF-8" />
            <!-- The above 3 meta tags must come first in the head -->
    
            <title>Test: Displaying Errors</title>
    
            <script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
    
            <script type="text/javascript">
                $(document).ready(function () {
                    $('#testButton').click(function (event) {
                        $.ajax({
                            method: 'post',
                            dataType: 'html',
                            url: 'test.php',
                            data: {},
                            success: function (response, textStatus, jqXHR) {
                                $('#result').html('Successful test... Unfortunately :-)');
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                /*
                                 * When an HTTP error occurs, errorThrown receives the textual portion of
                                 * the HTTP status, such as "Not Found" or "Internal Server Error". This
                                 * portion of the HTTP status is also called "reason phrase".
                                 */
                                var message = errorThrown;
    
                                /*
                                 * If a response text exists, then set it as message,
                                 * instead of the textual portion of the HTTP status.
                                 */
                                if (jqXHR.responseText !== null && jqXHR.responseText !== 'undefined' && jqXHR.responseText !== '') {
                                    message = jqXHR.responseText;
                                }
    
                                $('#result').html(message);
                            }
                        });
                    });
                });
            </script>
        </head>
        <body>
    
            <h3>
                Test: Displaying Errors
            </h3>
    
            <div id="result">
                Hier comes the test result. Since an error is thrown, I expect it to appear hear.
            </div>
    
            <br/>
    
            <form method="post" action="">
                <button type="button" id="testButton" name="testButton">
                    Start the test
                </button>
            </form>
    
        </body>
    </html>
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   Mike    6 年前

    这个 success error jQuery AJAX调用中的函数只是检查请求的HTTP状态代码当php产生错误时,它不会更改状态代码,因此jquery触发 成功 功能。如果要使用jquery错误,则必须更改状态代码。你可以通过抓住 Error (php>=7):

    try {
        $data = test();
    }
    catch (\Error $e) {
        http_response_code(500);
        echo $e->getMessage();
    }
    

    或者你可以保持状态码为 200 (默认)并用json发送您的响应,包括您喜欢的success和error属性,以及您可能希望随请求返回的任何其他内容。

    header('Content-type: application/json');
    $response['success'] = true;
    $response['error'] = null;
    try {
        $data = test();
    }
    catch (\Error $e) {
        $response['success'] = false;
        $response['error'] = $e->getMessage();
    }
    echo json_encode($response);
    

    并确保移除 dataType 属性使jquery自动确定类型头。

    如果你的程序意外地抛出错误,这可能意味着你做错了什么。如果你希望它抛出错误,你需要抓住它们。这要么意味着用try/catch块包装,要么是 set_exception_handler() 我是说, set_error_handler() register_shutdown_function() 在全球范围内实现这一目标。