如何在jQuery的load()方法中捕获错误

51 ajax error-handling jquery load

.load()当用户点击按钮时,我正在使用jQuery的方法来检索一些数据.

加载成功完成后,我将结果显示在a中<div>.

问题是,有时在load()检索数据时会发生错误.

我怎样才能发现错误load()

cgp*_*cgp 77

load()文档.

关于加载错误如何发生的一点背景......

$("body").load("/someotherpath/feedsx.pxhp", {limit: 25}, 
    function (responseText, textStatus, req) {
        if (textStatus == "error") {
          return "oh noes!!!!";
        }
});
Run Code Online (Sandbox Code Playgroud)

编辑:添加注释请求的根路径以外的路径.


mat*_*t b 11

除了像ÓlafurWaage所建议的那样将回调传递给load()函数之外,您还可以注册"全局"错误处理程序(对于页面上的所有ajax调用,全局为全局).

注册全局Ajax错误处理程序至少有两种方法:

只注册错误处理程序ajaxError():

$.ajaxError(function(event, request, settings) {
      alert("Oops!!");
});
Run Code Online (Sandbox Code Playgroud)

或者,用于ajaxSetup()同时设置错误处理程序和其他属性:

$.ajaxSetup({
    timeout: 5000,
    error: function(event, request, settings){
        alert("Oops!");
    }
});
Run Code Online (Sandbox Code Playgroud)


Óla*_*age 6

load()提供回调.

打回来.
ajax请求完成时调用的函数(不一定成功).

这是它如何完成IIRC.(尚未测试过)

$("#feeds").load("feeds.php", {limit: 25}, 
    function (responseText, textStatus, XMLHttpRequest) {
        // XMLHttpRequest.responseText has the error info you want.
        alert(XMLHttpRequest.responseText);
});
Run Code Online (Sandbox Code Playgroud)

  • 函数IS responseText的第一个参数.无需使用XMLHttpRequest.responseText ... (8认同)