jQuery .load() 完成后的动作

jQuery action when .load() is done

我试图让一个动作在我的 load() 请求完成时开始,但 alert 从未出现。 load() 请求有效,因为我可以在 .haha div 中看到 mypage.html 的内容。这是真正简单的代码:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

Hello
<div class="haha"></div>

<script type="text/javascript">
    $(document).ready(function(){
        $('.haha').load('mypage.html', function(xhr) {
            if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
                alert('TEST TEST'); 
            }
            alert('TEST TEST'); 
        });
    });
</script>

None 的警报出现。

编辑: 在我的控制台中我有这个:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
FAToolbar.js:1 Uncaught TypeError: $.cookie is not a function

如果您查看 load() 的文档,您会发现 xhr 对象是传递给回调函数的第三个参数。您的代码很可能在尝试访问不存在的返回字符串的属性时生成语法错误,这会停止进一步执行。试试这个:

$('.haha').load('mypage.html', function(response, status, xhr) { // note the extra params
    if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
        alert('TEST TEST'); 
    }
    alert('TEST TEST'); 
});

首先,函数 load 的回调参数仅在请求完成后调用,因此您不必检查 xhr.readyState == 4
其次,你通过函数 load 加载了一个 html,我猜页面 mypage.html 包含一些 javascript 代码,一些代码调用函数 $.cookie page.So 页面 mypage.html.

中的 js 代码在控制台产品中打印的错误不包括在内