2

I want to give a response from the server like this:

{foo: "some value", bar: function(){console.log(this);}}

But if I write the response line in the controller like so:

render json: {foo: "some value", bar: 'function(){console.log(this);}'}

The result will be as follows:

{foo: "some value", bar:"function(){console.log(this);}"}
2
  • Results will be converted to String, you can remove " from the result. Commented Jun 4, 2015 at 8:06
  • I thought that there are ready tools for this. Or bar must be custom object, not simple string. Commented Jun 4, 2015 at 8:40

3 Answers 3

1

Don't use eval — it's unsafe and tricky. Wrap your function body with quotes, remove keyword function out of there and then create new function on the clientside with function constructor.

JSON:

{ 
   "fn": "alert(arguments);"
}

Clientside parsing code:

var myFunction = new Function(JSON.parse(jsonString).fn);

This is better because your function won't automatically execute any code or expose itself to the global context.

The only considerable inconvinience is the absence of arguments list. You have to use arguments object instead.

Sign up to request clarification or add additional context in comments.

1 Comment

And furthermore: think about your application design a bit more. Maybe there's something wrong if you have to send functions to the client?
1

use this on server side:

render json: {foo: "some value", bar: 'function(){console.log(this);}'}

Now you can post-process the parsed JSON:

json.bar = eval(json.bar);

Comments

1

The server will always return you the value in string for your JS code part.

You can however the JS code using eval function.

like this:

eval(response.bar)

Given that:

response = {foo: "some value", bar:"function(){console.log(this);}"}

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.