2012-06-01 101 views
1

我有一個javascript函數,我正在傳遞一個函數名,我需要在調用ajax之後調用。 ajax調用返回一些包含對js文件引用的html。傳遞給我的函數的functionName在html中,但它引用了js文件中的一個對象。我注意到對象有時存在,有時不存在。有沒有辦法確保對象始終存在(或等待它存在),然後只調用JavaScript函數。請注意,我不知道對象變量是什麼,所以有一種方法可以確保腳本文件已經在dom中加載,然後調用該函數。AJAX調用後調用Javascript函數

function(functionName) 
    { 
     $.ajax({ 
    url: properties.url, 
    type: properties.type, 
    data: properties.data, 
    dataType: properties.format, 
    success: function (data) { 
    // data contains <div>myname</div><script src="/myfile.js" type="text/javascript"></script> 
    // Put the data in some div 
    BindData(data); 

    // How to ensure that the script myfile.js is loaded in dom before I call eval 
    eval(functionName); 
    } );  

    } 
+0

你能提供你的'GetAjaxData'代碼?該解決方案可能需要傳遞該函數的回調。 – apsillers

+0

對不起。你的權利。 eval代碼在ajax調用的成功部分中。我將其編輯爲 –

+0

以上嘗試['ajaxSuccess()'](http://api.jquery.com/ajaxSuccess/)方法。 – undefined

回答

2
function(functionName) 
    { 
     $.ajax({ 
    url: properties.url, 
    type: properties.type, 
    data: properties.data, 
    dataType: properties.format, 
    success: function (data) { 
    // data contains <div>myname</div><script src="/myfile.js" type="text/javascript"></script> 
    // Put the data in some div 
    BindData(data); 

    //ensure the script has loaded. 
    $.getScript($('script:first',data).attr('src'), function(){ 
      eval(functionName); 
    }); 

    });  

    } 
0

您可以嘗試在ajax調用結束之前觀看數據。 不知道,但如果數據是「不確定」,你可以檢查這樣的事情

var data = GetAjaxData(); 
while(typeof data === undefined); 
bind, eval ecc ecc 

但如果GetAjaxData返回別的東西這種情況將會改變。 你可以嘗試同樣的事情,但做之前:

var data = null; 
data = GetAjaxData(); 
while(data == null); 
do stuff 

您也可以嘗試$就與jQuery的成功處理程序回調 希望幫助