2012-01-02 88 views
0

我已经阅读了关于JQuery Ajax调用失败参数的几篇文章,但没有直接回答我的问题。如果你想在这里对我的起跳点读了起来,这一职位将是一个良好的开端:JQuery Ajax失败并返回异常?

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

我的问题是,有事情了一把,可能会导致我的申请失败 - 如果我脚本返回false上面的方法对我来说工作得很好(如果我理解正确的话),但是大多数情况下我的脚本会通过踢出使用Zend Framework处理的异常而失败。我宁愿返回异常,以便可以向用户提供更详细的消息。是否有可能让我的PHP脚本返回一个值,同时让Ajax调用知道它是一个失败?

+1

相关的主题 - http://stackoverflow.com/questions/2947757/zend-framework-how-to-handle-exceptions-in-ajax-requests – adatapost 2012-01-02 06:45:38

回答

2

当然可以。首先,你需要你归类错误,例如:

  • 严重错误
  • 例外
  • 虚假/错误状态

我劝你把作为正确的返回值并没有错误处理 - 0。在所有其他情况下那将是一个错误

另一个有用的建议是使用JSON作为客户端 - 服务器对话。

在PHP这将是:

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

在这种情况下,你可以通过错误代码和消息,并在$额外的附加参数,可以例如,该呼叫:

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

响应从服务器端将是:

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

对于客户端你需要一个包装函数$ .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); 
       } 
      } 
     } 
    }); 
} 

以及函数来验证JSON,以便如果损坏的格式到来。

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; 
} 

裹在的try-catch你的代码,并在catch语句做这样的事情:

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

的结果将是您收到浏览器控制台调试信息,并能处理错误/异常( prepareJSONResponse())和fatals(通过读取HTTP状态头,如果它不是200,那么出现错误)。

希望多数民众赞成你问。

+0

你不可能在这里更有帮助。你最诚挚的感谢。 – drewwyatt 2012-01-03 05:24:37

+0

不客气...) – devdRew 2012-01-03 06:12:20