开发者

jquery: calling a function

Okay I am working with some jquery creating dynamic popups. However, periodically the response will be the name of a function that I need to call instead of actual data and I am trying to figure out how to do this..

success: function(response) {
                                var obj = $.parseJSON(response);
                                if (obj.response == 'false') {
                                    $('#popuperrDisplay').html(obj.msg);
                                    $('#popuperrors').show();
                                } else {
                                    if (obj.response == 'redirect') {
                                        window.location.href = obj.msg; 
                                    } else if (obj.response == 'function') {
                                        call obj
                                    } else {
                                        $(this).dialog('close');
                                    }
                                }
                            }

This is the current portion of my jquery. I开发者_如何学Python need to figure out how I can send the name of a JS function through json_encode and have JS actually call that function


If the function is defined globally (on the window object), you could simply invoke it like so:

if (obj.response === 'function' &&            // 1
    typeof window[obj.msg] !== 'undefined') { // 2

    window[obj.msg]();                        // 3
    // or...
    window[obj.msg].apply(null, obj.args);    // 4
}
  1. checks whether the type of the response is a function.
  2. checks if there is a function with the given name defined on the window object.
  3. calls that function.
  4. calls that function and provides it with an array of arguments.

Edit: (window[] syntax)

To further clarify, window['showPopup'] accesses the showPopup member of the window object. It's the same as doing window.showPopup. Only, the [] syntax has the advantage of receiving a string instead of actual code.

window['showPopup'] will return an object (if defined); let it be a function for our particular example.

We then call that function object by using the () operator, like so: window['showPopup'](). Once again, this is the same as doing this: window.showPopup().

Edit 2: (invoke with arguments)

If the function has to be invoked with an array of arguments, we can use apply. Invoking the function would then look like:

window['showPopup'].apply(null, arrayOfArgs);

Where arrayOfArgs is an array containing the arguments.


If I understand the question correctly, the server is sending back objects in one of the forms:

{"response":"false", "msg":"some message"}

{"response":"redirect", "msg":"some message"}

{"response":"function", "msg":"functionName"}

and the parsed string will become an object called obj.

In the latter case I am assuming the value of msg is the name of the function to call. You could invoke this with

window[obj.msg]()

Best to check that it is a function with typeof first (see Bryan's answer).

Also make sure the name of the function that the server is sending back is a function you expect it to send back. You don't want to call anything blindly. At least it appears you are expecting it to send back function names and not arbitrary code, but still, be safe!


If you have a function in a variable named x and you want to call that function, there are several ways you can do that.

function doAlert(msg) {
    alert(msg);
}

var x = doAlert;

x("hi");
x.call(this, "hi");
x.apply(this, arrayOfArguments);

See here for more info on .call(). See here for more info on .apply().

If you have a string that represents a function name and you want to call the corresponding global function with that name, you can do so via the window object.

function doAlert(msg) {
    alert(msg);
}

var name = "doAlert";
window[name]("hi");

It is also possible, though not generally recommended, to use eval:

function doAlert(msg) {
    alert(msg);
}

var name = "doAlert";
eval(name + '("hi");');

You asked this question in a comment:

Say i have a function inside functions.js named updateAll that has no parameters... in my php, my json would be $data['function_name'] = 'updateAll'; which would get encoded with json_encode()... turning that into obj.function_name so could I not just call: obj.function_name(); and have it work?

Here's my answer to that new question:

I'm not sure I fully understand your question, but I'll try to describe various possible aspects of your question.

If function_name is a variable, you can't use obj.function_name(). That syntax only works for string constants (not variables).

If you have a method name in a variable, you can always do the same thing as the dot notation by using [] like this: obj[function_name]();

If the function name is in $data['function_name'] = 'updateAll' and that function name is actually a method on the obj object, such that what you want to call is `obj.updateAll', then the way you could do that would like this:

obj[$data['function_name']]();

Remember that in Javascript, anywhere that you would use the .x reference for a name that was known ahead of time, you can use the [x] reference for a name that is in a variable.

If (as you posted in a comment), your JSON looked like this:

{"response":"function","msg":"someFunction","attribs":{"id":"1","p_id":"2"}}

and that JSON meant that you wanted to call the function someFunction() and pass it the parameters in attribs, then there are a couple ways to do that depending upon how you want the arguments passed to the function. If you want the args passed as the attribs object, you'd do it like this:

var data = {"response":"function","msg":"someFunction","attribs":{"id":"1","p_id":"2"}};
if (data.response == "function") {
    data.msg(data.attribs);
}

If you wanted the arguments passed as normal parameters with the id parameter first and the p_id parameter second, you'd do it like this:

var data = {"response":"function","msg":"someFunction","attribs":{"id":"1","p_id":"2"}};
if (data.response == "function") {
    data.msg(data.attribs.id, data.attribs.p_id);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜