2015-09-02 88 views
0

我創建了包含對服務器執行POST和GET請求的AJAX函數的control.js文件。從包含AJAX函數的JavaScript文件返回數據

問題是,我無法將從Control.js文件中的AJAX函數收到的數據返回給其他JavaScrip文件。

我知道我們不能直接從異步函數返回數據。它需要額外的函數來處理從函數返回的數據。

function getServer(directory) 
    { 
     xmlHttp.open("GET",rootDirectory+directory); 
     xmlHttp.onreadystatechange = function(){ 
      if(xmlHttp.readyState == 4) 
      { 
       if(xmlHttp.status == 200) 
       { 
        Handler(xmlHttp.responseText); 
       } 
      } 
     }; 
     xmlHttp.send(); 
    } 
function Handler(response) 
{ 
     return response; 
} 

函數處理程序將數據正確地返回到它自己的文件(在control.js文件內)中的每個函數調用。

現在,假設我有多個JavaScript文件,並且我想調用此函數。我怎樣才能得到從這個文件中的函數返回的值?

實施例:

function construct() 
{  
    // This function belongs to load.js file not control.js 
    var handler = getServer("request/read.php?table=tasks");   
    console.log(handler); // This one return nothing...// 
} 

回答

0

傳遞Handler函數作爲參數,而不是硬編碼到函數。

getServer("/foo/bar/", myFunction);