2015-12-21 80 views
1

我试图在我的load()请求完成时开始动作,但alert从不出现。请求load(),因为我可以在.haha div中看到mypage.html的内容。这是非常简单的代码:完成.load()完成后的jQuery动作

<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> 

没有警报出现。

编辑: 在我的控制台我有这样的:

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 
+0

你为什么要检查xhr状态? – Vixed

+0

那么,在XHR状态下,它应该告诉我什么时候我的请求已完成并准备就绪。但尽管如此,使用或不使用它,它不工作 – Couteau

+0

你不需要检查它。添加功能在最后它会起作用。删除if和函数变量。 **('。haha')。load('mypage.html',function(){alert('TEST TEST')}); ** – Vixed

回答

3

如果您检查文档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'); 
}); 
+0

Oke所以我试了一下:http ://corleonesi.forumactif.org/h3-foufou(对不起,我不能做一个jsfiddle由于负载()) 它仍然不显示警报 – Couteau

+0

在我的控制台中,我有: “Synchronous XMLHttpRequest因为它对最终用户的体验有不利影响,因此不推荐使用主线程。如需更多帮助,请查看http://xhr.spec.whatwg.org/。 FAToolbar.js:1 Uncaught TypeError:$ .cookie不是功能“ – Couteau

+0

的首先是一个警告,而不是一个错误,因为你已经在代码中的某处设置了'async:false' - 我强烈建议你移除它。第二个错误是因为在尝试使用它之前你没有包含jQuery cookie插件。这些错误都与您在问题中显示的代码无关。 –

0

第一,功能负载的回调参数请求完成后才会被调用,所以您不必检查xhr.readyState == 4
第二,你通过功能load加载html,我想页面mypage.html包含一些javascript代码,并且一些代码调用了功能$.cookie,它不包含在页面中。所以错误在你的控制台产品中打印出来js代码从页面mypage.html