2015-12-21 75 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