2

从AngularJS 的源代码中可以看出,任何返回 200-299 范围内的 HTTP 代码的 $http.post 请求都会触发 success() 回调,即使响应包含无效数据(例如无效的 JSON)。

我专门设置了我的呼叫responseType: 'json',即使这样,当其他事情回来时也会触发成功回调。这在打开 PHP 的 display_errors 设置的开发服务器中尤其令人讨厌。当服务器端出现问题并且 PHP 输出错误消息时,AngularJS 应用程序不会检测到这一点并愉快地继续。

有没有办法防止这种情况?我的意思是,当响应数据是无效的 JSON 时,让 AngularJS 应用程序触发 error() 回调?

谢谢

4

1 回答 1

2

so your PHP server responds with a 200 error code even on an error? Not knowing PHP, this feels like a server configuration problem to me. I'd expect a 500 error with a payload. That being said, there are two things that I can think of offhand.

$http includes transformResponse handlers you can set up to inspect the response for problems.

$http also includes the concept of "interceptors" which allow you to pick up the response payload and do something with it. You could use an interceptor to "reject" the response.

More information on transformResponse and "interceptors" in the $http documentation: http://docs.angularjs.org/api/ng.$http

于 2013-08-31T19:44:13.457 回答