【问题标题】:jQuery .load() error state?jQuery .load() 错误状态?
【发布时间】:2012-09-14 16:29:14
【问题描述】:

我似乎无法让这个解决方案为我工作。

How to catch error in jQuery's load() method

这是我正在尝试的代码。

$("#a").load("load.html", function(responseText, textStatus, XMLHttpRequest) {
        if (textStatus == "error") { alert("fail"); }
        else { alert("success"); }
});

当 load.html 存在时,它工作正常,但当它不存在时,什么都没有发生。这是有道理的,因为如果失败,它不应该进入回调。

有人能指出我哪里出错了吗?当 URL 不存在时,我试图让它抛出一个错误。

如果这会影响任何事情,我正在尝试使用 jQuery 1.3.2。

更新 问题似乎是因为我在本地而不是在服务器上工作。在线上传了我的文件,它似乎工作正常,jQuery 的某些部分需要服务器才能运行吗?

更新 进行了更多测试并使用带有错误回调的 .load() 无法离线工作,但 .ajax() 可以。对为什么感到困惑,但我们开始了。

【问题讨论】:

  • 可能是来自服务器的请求状态为“OK”且正文为空。在这种情况下,您不会收到任何错误。因为你有空的和正确的页面。看看api.jquery.com/jQuery.get,但在这种情况下,您应该添加将结果添加到元素中的代码
  • jQuery 1.3.2 真的很老了,就像那样。

标签: javascript jquery


【解决方案1】:

试试这个

$.ajax({

    url: 'load.html',
    dataType: 'html',
    success: function(data) {
         //handle data object containing the html
         $('#a').html(data);
    },
    error: function(xhr, error){
        //generic error callback, you'll end up here when your file doesnt exist
    }

});

【讨论】:

    【解决方案2】:

    你可以在这里试试:

    <div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
    <button>Get External Content</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("#div1").load("demo_tes.txt", function(responseTxt, statusTxt, xhr){
                    if(statusTxt === "success")
                        alert("External content loaded successfully!");
                    if(statusTxt === "error")
                        alert("Error: " + xhr.status + ": " + xhr.statusText);
                });
            });
        });
    </script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多