将可选函数作为参数传递给另一个函数

时间:2011-12-16 18:43:09

标签: javascript jquery

我想如何调用函数的选项:

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是否为函数?

谢谢!

2 个答案:

答案 0 :(得分:1)

不是针对未知类型进行测试,而是验证函数确实是函数:

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

但是,您当前的代码不会阻止successFunc运行。确保成功处理AJAX请求(没有错误没有跨域限制)。

由于您的代码没有事件到达调用successFunc的位置,因此可能会在if (typeof ...之前生成错误。

答案 1 :(得分:0)

测试typeof successFunc是“function”可以解决这个问题:

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);
      }
    }
  });
}