2011-12-16 9 views
0

オプション:別の関数のパラメータとしてオプション機能のパス

myAjax("http://ajaxurl.com", { prop: val }, function(resp) { alert(resp); }); 

または

function handleSuccess(resp) { alert(resp); } 
myAjax("http://ajaxurl.com", { prop: val }, handleSuccess); 

または

myAjax("http://ajaxurl.com", { prop: val }, null); 

または

myAjax("http://ajaxurl.com", { prop: val }); // param not even provided 

これはmyAjax関数定義でどのように処理できますか?このようなもの...?

function myAjax(url, jsonData, successFunc) { 
    $.ajax({ 
    ... all the necessary ajax stuff that normally goes here 
    , success: function(response) { 
     // custom myAjax success handling goes here. this must happen before optionally-passed-in successFunc gets executed 

     // what goes here? this? 
     if (typeof successFunc != 'undefined' && successFunc != null) { 
     successFunc(response); 
     } 
    } 
    }); 
} 

私は上記のようなことを試みましたが、成功関数を呼び出さなかった。 successFuncが関数であるかどうかチェックする必要がありますか?

ありがとうございます!

+0

'typeof演算successFunc ==「function'' – Kenaniah

+0

の代わりに、またはそれに加えての?ありがとう! –

答えて

1

代わりに未知の種類に対するテスト、機能が実際に関数であることを確認します。

if (typeof successFunc == 'function') { 
    successFunc(response); 
} 

は、あなたの現在のコードは、しかし、実行されてからsuccessFuncを防ぐことはできません。 AJAXリクエストが正常に処理されていることを確認します(エラーはドメイン間の制限なし)。

あなたのコードはイベント番号successFuncに到達しないため、if (typeof ...より前にエラーが発生している可能性があります。

0

typeof演算successFuncは、 "機能" であることをテストするには、トリックを行います:

function myAjax(url, jsonData, successFunc) { 
    $.ajax({ 
    ... all the necessary ajax stuff that normally goes here 
    , success: function(response) { 
     // custom myAjax success handling goes here. this must happen before optionally-passed-in successFunc gets executed 

     // what goes here? this? 
     if (typeof successFunc === 'function') { 
     successFunc(response); 
     } 
    } 
    }); 
} 
関連する問題