【发布时间】:2020-07-18 05:28:45
【问题描述】:
使用 jQuery Ajax 函数时,当指定错误和成功处理程序时,您会期望指定的错误处理程序函数捕获无效文件和 404 错误,但由于某种原因我的代码没有。
代码:
// using jQuery 3.4.1
// this code has been taken from a larger function, but the issue can be replicated by pasting
// the following code into the JS Console.
var scriptPath = 'http://mywebserver.localhost/application/invalid.js';
jQuery.ajax( {
async: false,
type: 'GET',
url: scriptPath,
crossOrigin: false,
data: null,
global: false,
cache: true,
success: function() {
debugger;
// do some stuff
onResult();
},
error: function( jqXHR, textStatus, errorThrown ) {
debugger;
Lib.showNetworkErrorAlert( jqXHR, textStatus, errorThrown );
},
dataType: 'script'
} );
这会导致:
未捕获的错误来自:~unknown~
错误:未捕获的 SyntaxError:意外的标记“http://mywebserver.localhost/........ 行:1
澄清一下,我已经查看了那里的 SO 问题,但我发现的问题往往集中在错误的原因上。我知道错误'Unexpected token
我试图找出和理解的是为什么会出现此错误而不是指定的正常错误处理程序。至少我会认为将 dataType 设置为 script 会使其实现稍微好一点的错误,嘿,这是一个 HTML 404 错误文件,而不是脚本。
非常感谢任何帮助和见解。
更新:这是开发工具中的网络选项卡,显示它正在返回 404。
【问题讨论】:
-
除了这个问题,如果你想动态加载 JS,使用
$.getScript(),而不是$.ajax() -
error:仅在响应包含状态错误代码时触发,例如不是 2xx(例如 200)。在这种情况下,您的服务器返回 200 http 状态代码,但带有“404”错误文件 - jquery 无法判断返回的 HTML 是针对 404 错误页面,它只是文本 - 您的服务器配置不正确. -
您可以随时为您的 ajax 请求指定
dataType:"string",然后在自己解析之前自行检查。 -
@RoryMcCrossan 谢谢,我会检查一下。
-
@freedomn-m 根据我在开发工具中的网络选项卡,正在返回正确的 404
标签: javascript jquery ajax error-handling