2012-03-23 13 views
0

私はJavaScriptファイルの中にAJAX関数を持っています。私はそれを抽象的にし、グローバル変数を使わないようにします。関数をパラメータとして使用できますか?

AJAXは、データベースにイベントを挿入します。

function insertCalendarEvents(calendar_group, event_name, event_datestart, event_datestop, event_timestart, event_timestop, event_info, onFinish) { 
    var request; 
    if(window.XMLHttpRequest) 
     request = new XMLHttpRequest(); 
    else 
     request = new ActiveXObject("Microsoft.XMLHTTP"); 

    request.onreadystatechange = function() { 
     if (request.readyState == 4 && request.status == 200) { 
      if(request.responseText.substr(0, 6) == "error ") 
       alert(errorName[request.responseText.substr(6)]); 
      else { 
       var event_id = request.responseText; 
       //call onFinish function with parameter event_id which database assigned it 
      } 
     } 
    } 

    request.open("GET", "php/calendar.php?action=insertCalendarEvents&calendar_group=" + calendar_group + "&event_name=" + event_name + "&event_datestart=" + event_datestart + "&event_datestop=" + event_datestop + "&event_timestart=" + event_timestart + "&event_timestop=" + event_timestop + "&event_info=" + event_info, true); 
    request.send(); 
} 

機能は、私が何をしたいので、非同期であり、それはデータベースにデータを挿入終わった瞬間に、私はそれを実行したいです私はそれをパラメータとして与えます。

これを実現する方法について良いアイデアがあれば、私はそれを聞いて、本当に幸せになる:)

は、事前にダニエルありがとうございます!

+1

あなたは '(EVENT_ID)onFinish'てみましたか? – pimvdb

+0

私はちょうどそれをtryed、それは動作するようです:) 私は(function(){// stuff})使用された関数を呼び出した。パラメータゾーン –

+0

の中で、Ajaxのコールに役立つようにJavaScriptライブラリ(jQuery:http://api.jquery.com/jQuery.ajax/など)を使用することを検討することをお勧めします。 – jlb

答えて

2

関数は、渡すことができるオブジェクトです。唯一の余分なことは、あなたが()を使ってそれらを呼び出すことができるということです(もちろん引数もあります)。

ちょうどいいところにそれらを渡すことができます。スコープなどのすべての情報は保持されます。だから、これは動作するはずです:

onFinish(event_id); 

を基本的には、より簡単な例では、このようになります:

function func() { 
    alert("func is being run"); 
} 


func(); // works 


function callFunction(f) { 
    f(); 
} 

callFunction(func); // pass func; works 


callFunction(function() {    // pass a function on the fly; works 
    alert("function passed directly"); // (nothing special in fact) 
}); 
+0

はい、このアイデアを使ってこの問題を解決しました私はそれが複雑な問題ではないことを理解していますが、私はちょうどjqueryとjavascriptで一般的に1ヶ月のように作業を始めて以来、私のためだった:)大変ありがとう、ダニエル。 –

関連する問題