5

i have a very little problem but don't know how to solve it. I need to send a JSON with a function, but with parameters and this is my problem.

Sending a function in JSON is simple:

var jsonVariable = { var1 : 'value1', var2 : 'value2', func: function(){ alert('something'); } };

I need something else, need to pass the func function as parameter with parameters.

Example:

var jsonVariable = { var1 : 'value1', var2 : 'value2', func: funcParam(param1,param2) };
function(parameter1, parameter2){
     alert(parameter1 + parameter2);
}

But this don't work :(

Any help with this will be really appreaciated

1
  • 5
    That is not JSON. JSON does not have the concept of functions. It is simply a JavaScript object. You have to be more clear about what you want to send, where and how. Commented Nov 24, 2011 at 14:43

4 Answers 4

1

It's a bit unclear what you want, but if you want to define a function which accepts parameters, you'll want something like this;

var jsonVariable = { var1 : 'value1', var2 : 'value2', func: function(param1, param2){ alert(param1 + param2); } };
Sign up to request clarification or add additional context in comments.

Comments

1

Are you looking to be able to pass any number of parameters to the function? If so, try passing an array to your function and iterate through, eg:

var jsonVariable = {
    var1 : 'value1',
    var2 : 'value2',
    func: function(params){
        var alertString = "";
        for (var i = 0; i < params.length; i++)
            alertString+=params[i]+" ";
        alert(alertString);
    }
};

and call it using

jsonVariable.func(["param1", "param2"]);

Fiddle

Comments

0

You can create a function that has closed over those arguments:

var send_func = (function( param1, param2 ) {
    return function(){
        alert(param1 + param2);
    };
}( 3, 4 ));

var jsVariable = { var1 : 'value1', var2 : 'value2', func: send_func };

So the outer function above is invoked, receives the arguments, and returns a function that when invoked uses those original arguments.

another_func( jsVariable );

function another_func( obj ) {

    obj.func();  // 7

}

Of course this has nothing to do with JSON. You won't be able to serialize any part of the functions.

Comments

0

Take a look at the JSONfn plugin.

http://www.eslinstructor.net/jsonfn/

It does exactly what you need.

-Vadim

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.