如何在字段中使用JS函数在Rails中呈现JSON?

时间:2015-06-04 08:05:33

标签: ruby-on-rails json render

我想从服务器给出这样的响应:

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

但如果我在控制器中编写响应行,那么:

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

结果如下:

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

3 个答案:

答案 0 :(得分:1)

在服务器端使用它:

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

现在您可以对已解析的JSON进行后期处理:

json.bar = eval(json.bar);

答案 1 :(得分:1)

服务器将始终返回JS代码部分的字符串值。

但是你可以使用eval函数来获取JS代码。

像这样:

eval(response.bar)

鉴于:

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

答案 2 :(得分:1)

不要使用eval - 这是不安全和棘手的。用引号包装函数体,从中删除关键字函数,然后在函数构造函数的clientide上创建新函数。

JSON:

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

Clientside解析代码:

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

这样做更好,因为您的函数不会自动执行任何代码或将自身暴露给全局上下文。

唯一相当不便的是没有参数列表。您必须改为使用arguments对象。