Passing function name as a parameter to another function
I am calling a web services from client side on .aspx page, and I want to call a function on the success of this service.
The name of function will be passed as a parameter to this function, which will dynamically change.
I am passing it like this:
function funName parm1, parm2, onSucceedCallFuntion
function onSucceedCallFuntion(result)
//doing something here.
Perhaps because it's a string is why the "succeed" function could not be called
function funName(parm1, par2, onSucceedFunName) {
$.ajax({
url: "../WebServices/ServiceName.asmx/ServiceFunName",
data: JSON.stringify({
parm1: parm1,
par2: par2
}), // parameter map type: "POST", // data has to be POSTED
contentType: "application/json",
开发者_运维百科 dataType: "json",
success: onSucceedFunName,
});
function onSucceedFunName() {}
If you're passing the name of the function as a string, you could try this:
window[functionName]();
But that assumes the function is in the global scope. Another, much better way to do it would be to just pass the function itself:
function onSuccess() {
alert('Whoopee!');
}
function doStuff(callback) {
/* do stuff here */
callback();
}
doStuff(onSuccess); /* note there are no quotes; should alert "Whoopee!" */
Edit
If you need to pass variables to the function, you can just pass them in along with the function. Here's what I mean:
// example function
function greet(name) {
alert('Hello, ' + name + '!');
}
// pass in the function first,
// followed by all of the variables to be passed to it
// (0, 1, 2, etc; doesn't matter how many)
function doStuff2() {
var fn = arguments[0],
vars = Array.prototype.slice.call(arguments, 1);
return fn.apply(this, vars);
}
// alerts "Hello, Chris!"
doStuff2(greet, 'Chris');
精彩评论