如何通过作为参数传递的名称来调用函数?接下来是我的用例,我有一个switch case
,在其中设置了api ajax调用的data
,一旦完成了ajax,就应该调用print function
并将数据结果作为参数传递。我不确定这是否是一个好方法,是否有更好和更容易的方法来做我正在尝试的事情?也许使用async
/ promises
?
function printUpcoming(data) {
//stuff
}
function printRecently(data) {
//stuff
}
function printPopular(data) {
//stuff
}
function requestAjax(dataSend, callFunctionByName) {
$.ajax({
type: "POST",
url: "api-url",
headers: {
"Accept": "application/json",
"user-key": "userkey"
},
data: dataSend,
dataType: 'json',
success: function(data) {
jsonVal = data[0];
//Call the function print depending of switch case option
callFunctionByName(jsonVal);
}
});
}
switch (param) {
case "upcoming":
dataSend = "fields * where whatever 1";
functionName = printUpcoming();
requestAjax(dataSend, functionName);
break;
case "recently":
dataSend = "fields * where whatever 2";
functionName = printRecently();
requestAjax(dataSend, functionName);
break;
case "popular":
dataSend = "fields * where whatever 3";
functionName = printPopular();
requestAjax(dataSend, functionName);
break;
}
答案 0 :(得分:2)
一种选择是将功能分组为一个对象:
const Printer = {
upcoming(data) {...},
recently(data) {...},
popular(data) {...},
}
然后
requestAjax(dataSend, param)
和requestAjax
Printer[funcName](jsonVal))
@VLAZ建议的另一种选择是完全摆脱回调:
async function requestAjax(dataSend) {...}
...
printUpcoming(await requestAjax(...))
示例:
function printUpcoming(x) {
console.log('Upcoming!', x)
}
async function request() {
return $.ajax('https://jsonplaceholder.typicode.com/todos/1')
}
async function process(param) {
switch (param) {
case "upcoming":
printUpcoming(await request());
break;
case "recently":
printRecent(await request());
break;
}
}
process('upcoming')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
答案 1 :(得分:0)
相对于jQuery的fetch
,我推荐$.get
。要以其名称调用函数,可以使用eval
,,但我不建议使用eval!。这可能会导致安全风险和奇怪的错误。相反,您可以像这样创建函数索引:
const AJAX_HANDLERS = { printUpcoming, printRecently, printPopular };
然后使用提取:
async function requestAjax(dataSend, handlerFunction) {
if (typeof handlerFunction == "string") {
// Convert "name" to "printName"
const fnName = "print" + (handlerFunction).replace(/^([a-z])/i, (x, m1) => x.toLocaleUpperCase());
if (typeof AJAX_HANDLERS[fnName] == "function") {
handlerFunction = AJAX_HANDLERS[fnName];
}
else {
throw new Error("Invalid function callback name: " + fnName)
}
}
const fetchSettings = {
method: 'POST',
headers: {
"Accept": "application/json",
"user-key": "userkey"
},
body: dataSend
};
const result = await fetch("api-url", fetchSettings);
const jsonResponse = await result.json();
handlerFunction(jsonResponse[0]);
}