将可选函数作为参数传递给另一个函数
pass optional function as parameter to another function
如何调用函数的选项:
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);
}
}
});
}
相关文章:
- 在构造控制器、服务等时作为函数参数传递之前列出的角度 JS 变量
- 作为函数参数传递的匿名函数的范围
- 通过函数参数传递id
- 将数组值作为函数参数传递
- 是否需要初始化在 Javascript 中作为“类”构造函数参数传递的变量
- JavaScript 函数参数传递数组
- Angular2 将函数参数传递给构造函数
- 为什么我不能将角度变量作为函数参数传递
- jQuery - 基于作为函数参数传递的对象构建动态 if 语句
- 停止对作为函数参数传递到新列表的对象引用
- 在 JavaScript 中将数组作为内置函数参数传递
- AngularJS将范围变量名称作为函数参数传递
- Javascript 将对象作为函数参数传递
- 在对象上调用方法或将对象作为函数参数传递的差异
- 正确的方法:始终将所有变量作为函数参数传递
- 如何将动态创建的复选框值作为函数参数传递
- 节点简斯 |将对象作为函数参数传递
- 什么是将对象属性作为函数参数传递的良好策略/模式
- 将对象作为函数参数传递.不确定如何访问这些值
- 为什么我们要将函数参数传递到$scope$申请