如何用jQuery捕捉ajax是否得到了错误的响应类型

How to catch if ajax got wrong response type with jQuery

本文关键字:错误 响应 类型 jQuery 何用 捕捉 ajax 是否      更新时间:2023-09-26

我的ajax调用如下所示:

$.ajax({
     url: self.options.base_url + '/interface/jsonp/auth_user/',
     dataType: 'jsonp',
     success: function (data) {
         self._after_user_auth(data);
     },
     error: function () {
         self._service_unavailable()
     }
 });
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
    <title>Unhandled Exception</title>
</head>
<body>
    <h1>Unhandled Exception</h1>
    <p>An unhandled exception was thrown by the application.</p>
</body>
</html>

如果服务器端有一些错误,我会得到下一个响应

使Uncaught SyntaxError: Unexpected token < 上升

有可能在客户端上捕捉到这一点吗?

我不确定我是否理解你,但你可以用捕捉JavaScript错误

try{}catch(){}:

$.ajax({
     url: self.options.base_url + '/interface/jsonp/auth_user/',
     dataType: 'jsonp',
     success: function (data) {
         try{
             self._after_user_auth(data);
         }catch(err){
             console.log(err); //catch is fired if inside try js find an error.
         }
     },
     error: function () {
         self._service_unavailable()
     }
});

catch(err)-err是一个包含所有错误信息的对象。

一些文档:尝试捕获