ajax调用错误处理函数或if-else语句

ajax call error handling function or if-else statement

本文关键字:if-else 语句 处理函数 调用 错误 ajax      更新时间:2023-09-26

如果我已经使用了"if-else"语句,我想知道是否有必要在下面提到的示例中使用ajax调用错误处理函数:

我的型号:

 if ($query && $query->num_rows() > 0) {
        return $query->result();
    } else {
        return false;
    }    

我的控制器:

if ($this->model_users->did_get_data($user_id)) {
            $data["results"]= $this->model_users->did_get_data($user_id);           
            echo json_encode($data);            
        }
        else {      
        $data = array(
                    'message' => "Could not find any posts."
                     );
            echo json_encode($data);
        }

我的JS文件:

$.get('controller/get_data', function (data) {
        if (data.message !== undefined) {
            $( "#data_is_not_got").text(data.message);
        } else {
           //displaying posts               
        }
    }, "json");

是的,您仍然应该向AJAX调用添加一个错误处理程序。这将使您能够优雅地处理if/else语句没有涵盖的调用可能出现的任何数量的潜在问题-无法连接到服务器、内部服务器错误等。

这取决于控制器可能发生的情况。

如果你绝对确定不会有任何404错误或不会有任何超时错误,你可以在没有错误处理功能的情况下工作。但因为我确信你不能说它是100%确定的,我认为你必须实施它;)

但我的建议是:如果你不止一次使用AJAX调用,请创建你自己的"AJAX API",它只使用一个回调,你可以使用一个状态参数来告诉回调是否一切正常,所以实际上你只需要使用一个if-else语句。

这是我处理PHP后端的一个方法的一个简短示例:

ajax = function (callback) {
    $.ajax({
        // whatever you need here
        success: function (response) {
            if (typeof callback == "function") {
                callback(true, response);
            }
        },
        error: function (e) {
            if (typeof callback == "function") {
                if (e.statusText == "timeout") {
                    callback(false, {"timeout": true})
                } else {
                    try {
                        JSON.parse(e.responseText)
                        // if try is successfull, there is no fatal-error (which would exit the PHP, so no JSON)
                        callback(false, {})
                    } catch (x) {
                        // only maximum-execution-time-errors are fatal errors :P
                        if (e.responseText.indexOf('<b>Fatal error</b>') != -1) {
                            callback(false, {"timeout": true})
                        }
                    }
                }
            }
        },
    })
}