JQuery Ajax fail and return exception?

依然范特西╮ 提交于 2019-12-12 03:17:52

问题


I have read a few posts on fail parameters for a JQuery Ajax call, but none that have directly answered my question. If you want to read up on my jumping off point here, this post would be a good start:

jquery: is there a fail handler for $.post in Jquery?

My problem is that there are a handful of things that may cause my application to fail - if my script returns false the above method would work just fine for me (if I understand it correctly), but most of the time my script will fail by kicking out an exception that I handle using the Zend Framework. I would prefer to return the exception so that I can provide the user with a more detailed message. Is it possible to have my PHP script return a value while still letting the Ajax call know that it was a failure?


回答1:


Sure you can. First of all you need to categorize you errors, for example:

  • Fatals
  • Exceptions
  • false / error status

I would advise you to take as a return value for correct and with no errors processing - 0. In all other case that would be an error.

Another useful advise would be to use JSON as a client-server conversation.

In PHP it would be:

function prepareJSONResponse($code, $message, array $extra = array())
{
    return json_encode(array_merge(
        $extra, array(
            'code'    => (int) $code,
            'message' => $message)));
}

In this case you could pass error code and message, and additional params in $extra, for example, for this call:

prepareJSONResponse(1, 'Not enough data passed', array('debug' => true));

Response from server side would be:

{code:1,message:'Not enough data passed','debug': true}

For the client side you need a wrapper function for $.ajax:

// calback(result, error);
function call(url, params, callback)
{
    if (typeof params == 'undefined') {
        params = {};    
    }

    $.ajax({
        'type'      : "POST",
        'url'       : url,
        'async'     : true,
        'data'      : params,
        'complete'  : function(xhr) {
            if (xhr.status != 200) {
                if (typeof callback == 'function') {
                    callback(xhr.responseText, true);
                }
            } else {
                if (typeof callback == 'function') {
                    callback(xhr.responseText, false);
                }
            }
        }
    });
}

and function to validate JSON, in order if the corrupted format comes.

function toJSON(data){
    try {
        data = JSON.parse(data);
    } catch (err) {
        data = { 'code' : -999, 'message' : 'Error while processing response' };
    }

    if (typeof data.debug != 'undefined') {
        console.log(data.debug);
    }

    return data;
}

Wrap in try-catch you code, and in catch statement do something like:

try {
    ...
} catch (Exception $e) {
    exit(prepareJSONResponse(1, $e->getMessage(), array(
        'debug' => 'There was an error while I were processing your request')));
}

The result would be that you receive debug information in browser console, and could handle errors / exception (prepareJSONResponse()) and fatals (by reading HTTP-status header, if it's not 200, then there was error).

Hope thats what you asked about.



来源:https://stackoverflow.com/questions/8698057/jquery-ajax-fail-and-return-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!