2013-11-01 69 views
2

我有一個計算每個服務器性能的網站。其中一個要求是關於性能的中心局部頁面必須先完成加載才能在後臺執行另一個功能。當document.ready中的函數完成時執行js函數

該中心部分頁面使用ajax調用。他們在js文件的document.ready被定義:

$(document).ready(function() { 
// ajax call here 
// another ajax call here 
// third ajax call here 
}); 

然後我想要的文件準備好內部的功能之後要執行的函數完成:

function functionA() { 
// some codes here 
}); 

我嘗試使用這樣的:

$.when(document).ready(function() { 
}).done(functionA); 

但我不能讓它運行..任何建議將很樂意讚賞。提前致謝!

+1

你要執行的功能,當'document.ready'完成後,或當所有AJAX調用完成?兩件完全不同的事情。 – CodingIntrigue

+0

@Rraham - 當ajax調用完成時。 – Gerald

回答

1

AJAX中的第一個字母代表異步這意味着在您的document.ready事件結束時,它們可能會在其他地方進行一些處理。 document.ready不會等待他們完成。

您需要設置的jQuery使用.when告訴你,當所有三個AJAX調用完成:

// Document.ready 
$(function() { 
    // Any synchronous code you may do on DOM ready goes here 

    // Set up the promise 
    $.when(
     // Pass in all your AJAX calls. 
     $.ajax({ url: "/AjaxCall1?param=true" }), 
     $.ajax({ url: "/AjaxCall2?param=1" }), 
     $.ajax({ url: "/AjaxCall3?param=yup" }) 
    ).then(function() { 
     console.log("All AJAX requests finished"); 
    }, function() { 
     console.log("Something went wrong :("); 
    }); 
}); 
0

這裏是處理DOM就緒事件的方式和Ajax同時呼籲:

var init, ajax1, ajax2, domready; 
ajax1 = $.ajax({ url: '/1' }); 
ajax2 = $.ajax({ url: '/2' }); 
domready = $.Deferred(); 
$(domready.resolve); 
init = $.when(domready, ajax1, ajax2); 

http://api.jquery.com/category/deferred-object/

那麼你不需要關心上面不再代碼:

init.done(function() { alert('success'); }); 
init.fail(function() { alert('failure'); }); 
init.done(function ($, response1, response2) { 
    alert(response2[0]); // shows the data from the second Ajax call 
}); 

這裏是一個現場演示:http://jsfiddle.net/wared/s22dT/

關於您的嘗試,jQuery.when()返回它沒有ready方法的承諾對象:

$.when().ready() // TypeError: Object #<Object> has no method 'ready' 

http://api.jquery.com/jQuery.when/