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

pass optional function as parameter to another function

本文关键字:函数 参数传递 另一个      更新时间:2023-09-26

如何调用函数的选项:

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

谢谢!

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

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

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

因为你的代码没有到达调用successFunc的点,很可能在if (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);
      }
    }
  });
}