【问题标题】:Handling MySQL Errors when using Ajax使用 Ajax 时处理 MySQL 错误
【发布时间】:2013-08-15 05:42:53
【问题描述】:

在 PHP 代码和 Ajax 中添加了标头,但仍然没有乐趣。

在使用 Ajax 处理表单提交时,我无法处理 MySQL 错误。我有以下代码:

var url = "save.php"; // the script where you handle the form input.

    $.ajax({
        type: "POST",
        url: url,
        data: $("#frmSurvey").serialize(), // serializes the form's elements.


        success: function(jqXHR, textStatus, errorThrown){

                $('.sequence-container div').hide().delay( 2000 );
                $next.show().delay( 2000 );



        },
        error: function(jqXHR, textStatus, errorThrown){
            if (jqXHR.status === 0) {
                            alert('Not connect.\n Verify Network.');
                        } else if (jqXHR.status == 503) {
                alert('Error: ' + jqHXR.responseText);
            }    else if (jqXHR.status == 404) {
                            alert('Requested page not found. [404] - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist.');
                        } else if (jqXHR.status == 500) {
                            alert('Internal Server Error. [500] - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                        } else if (exception === 'parsererror') {
                            alert('Requested JSON parse failed - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                        } else if (exception === 'timeout') {
                            alert('Time out error - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                        } else if (exception === 'abort') {
                            alert('Ajax request aborted - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                        } else {
                            alert('Uncaught Error.\n' + jqXHR.responseText + ' - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                        }
          }

    }); 

这可以正常工作并处理任何错误,例如页面丢失等。

但是,我完全不知道如何处理/向用户显示实际提交到数据库时可能出现的任何错误。

目前我已经尝试过:

if ($mysql_error!="") {
        header('HTTP/1.1 503 Service Unavailable');
                    printf("Unexpected database error: %s\n", $mysql_error);
        mysqli_stmt_close($proc);
        mysqli_clean_connection($link);
        exit();
    }

但是由于页面没有显示(因为它是由 Ajax 提交的),所以不会出现错误消息。我认为我必须将该错误消息带回 Ajax 脚本中以将其显示给用户(对吗?) - 我不知道该怎么做。

任何指针/建议?

【问题讨论】:

    标签: jquery mysql ajax error-handling submit


    【解决方案1】:

    我会将你所有的错误逻辑从 jQuery 转移到 PHP。如果您想提供特定结果,您可以使用一个简单的 JSON 对象进行响应,该对象可以包含 status(成功或错误)、code(如果需要)、message,甚至是 data

    例如,您提出这样的请求:

    $.ajax({
      type: 'POST',
      url: url,
      data: $("#frmSurvey").serialize(),
      success: function(result){
        var json = $.parseJSON(result);
        if(json.response.status == 'success') {
          // do something
        } else {
          // look at message or code to perform specific actions
        }
      }
    });
    

    然后在处理此请求的 PHP 文件中,您构建一个包含所有上述元素(状态、代码、消息等)的数组。最终,你会echo 是这样的:

    $result = array(
      'response' => array(
        'status' => 'error',
        'code' => '1', // whatever you want
        'message' => 'Could not connect to the database.'
      )
    );    
    
    echo json_encode($result);
    

    $result 数组将包含基于您在 PHP 中所做检查的相关数据。

    希望这会有所帮助!

    【讨论】:

    • 感谢您的回复 - 非常感谢。我正在努力解决这个问题 - 心理障碍。我假设我需要在数组中添加成功和错误?
    • 得到了它 - 将数组放在 PHP 代码的错误和成功部分中,并进行相应的修改,它可以工作了!谢谢。
    • 另外一点,我会让错误报告对用户更加透明。记录错误并生成一封电子邮件给您,然后向用户提供简化的消息。用户真正需要知道的是他们的请求是否有效。如果有他们可以解决的问题,您可以让他们知道,除此之外,简单的“我们很抱歉,但我们的应用程序遇到了问题”就可以了。
    【解决方案2】:

    发送一个 503-Header

    <?php
    header('HTTP/1.1 503 Service Unavailable');
    

    你的 ajax 代码应该可以工作。

    编辑: 它将使用您的失败代码,您可以在函数中检查状态代码 503。

    jqXHR.status
    

    将是 503 并且

    jqXHR.responseText
    

    将包含您的消息。

    编辑2: js.文件

    var url = "save.php"; // the script where you handle the form input.
    
    $.ajax({
    type: "POST",
    url: url,
    data: $("#frmSurvey").serialize(), // serializes the form's elements.
    
    success: function(jqXHR, textStatus, errorThrown){
        if (jqXHR.status == 404) {
            alert('Error: ' + jqHXR.responseText);
        }else{
            $('.sequence-container div').hide().delay( 2000 );
            $next.show().delay( 2000 );
        }
    
    
    },
    error: function(jqXHR, textStatus, errorThrown){
        if (jqXHR.status === 0) {
                        alert('Not connect.\n Verify Network.');
                    } else if (jqXHR.status == 404) {
                        alert('Requested page not found. [404] - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist.');
                    } else if (jqXHR.status == 500) {
                        alert('Internal Server Error. [500] - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                    } else if (errorThrown === 'parsererror') {
                        alert('Requested JSON parse failed - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                    } else if (errorThrown === 'timeout') {
                        alert('Time out error - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                    } else if (errorThrown === 'abort') {
                        alert('Ajax request aborted - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                    } else {
                        alert('Uncaught Error.\n' + jqXHR.responseText + ' - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                    }
      }
    

    });

    保存.php:

    <?php
    header('HTTP/1.1 503 Service Unavailable');
    echo('hallo welt');
    exit();
    

    结果:

    Uncaught Error.
    hallo welt - Click 'OK' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist
    

    【讨论】:

    • 嗨,Markus,不确定以上内容会做什么?当页面不存在时,Ajax 代码可以工作并显示错误 - 上述内容是否有助于处理 mysql 返回的 error 消息?
    • @Homer_J 因为状态码不再是200,所以会导致jQuery进入错误回调而不是成功。
    • 感谢你们俩 - 只是想知道它去了哪里,然后,我仍然如何处理/显示任何返回的消息?
    • @Markus,好吧,这更有意义 - 会不会像 header: ('HTTP/1.1 503 Service Unavailable'); 一样 - 虽然我想知道这会在成功或失败部分中捕获吗?
    • 我仍然不清楚如果将数据提交到数据库时出现错误,它如何恢复 PHP 错误消息。我完全迷失了这一点。
    猜你喜欢
    • 1970-01-01
    • 2021-12-08
    • 2014-03-23
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 2018-03-25
    • 1970-01-01
    相关资源
    最近更新 更多