JQuery Ajax失败并返回exception?

我已经阅读了一些关于JQuery Ajax调用的失败参数的post,但没有一个直接回答了我的问题。 如果你想在这里阅读我的跳跃点,这篇文章将是一个良好的开端:

jquery:Jquery中有$ .post的失败处理程序吗?

我的问题是有一些东西可能导致我的应用程序失败 – 如果我的脚本返回false,上面的方法对我来说就好了(如果我理解正确的话),但大多数时候我的脚本会失败踢出我使用Zend Framework处理的exception。 我宁愿返回exception,以便我可以向用户提供更详细的消息。 是否有可能让我的PHP脚本返回一个值,同时仍然让Ajax调用知道它是一个失败?

你当然可以。 首先,您需要对错误进行分类,例如:

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

我建议你把正确的返回值作为error handling – 0 。 在所有其他情况下 ,这将是一个错误

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

在PHP中它将是:

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

在这种情况下,您可以传递错误代码和消息,以及$ extra中的其他参数,例如,此调用:

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

和函数来validationJSON,如果出现损坏的格式。

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

结果是您在浏览器控制台中收到调试信息,并且可以处理错误/exception(prepareJSONResponse())和致命(通过读取HTTP状态标头,如果它不是200,那么就有错误)。

希望这就是你所问的。