2012-08-07 58 views
0

我有以下代碼如何將js函數作爲參數發送給另一個函數?

function exec(param1,p2,fun){ 
    xmlhttp=new XMLHttpRequest(); 
    xmlhttp.onreadystatechange=function(fun){ 
     data=xmlhttp.responseText; 
     fun(data); 
    } 
    // rest ajax connection code 
} 

當我打電話

exec(param1,param2, 
    function(data){ 
     alert (data); 
    }); 

它說

對象不是一個函數

在定義

在行fun('test');

有什麼想法?

+5

適合我... http://jsfiddle.net/jHbsW/ – canon 2012-08-07 18:49:15

+0

也適用於我。 – Hubro 2012-08-07 18:49:51

+0

'console.log(fun)'(或'console.log(exec)')顯示什麼? – 2012-08-07 18:50:55

回答

1

你是在一個較窄的範圍內一個新的覆蓋fun

function exec(param1,p2,fun){ 
         ^^^ - The function you pass 

xmlhttp.onreadystatechange=function(fun){ 
            ^^^ - new variable (possibly an event object) 

更改變量名稱之一,所以你沒有掩蓋它的回調函數內。

相關問題