如何在字段中使用 JS 函数在 Rails 中呈现 JSON?
How to render JSON in Rails with JS function in field?
我想从服务器给出这样的响应:
{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);}"}
在服务器端使用这个:
render json: {foo: "some value", bar: 'function(){console.log(this);}'}
现在您可以 post 处理已解析的 JSON:
json.bar = eval(json.bar);
服务器将始终return您的 JS 代码部分的字符串值。
但是您可以使用 eval
函数的 JS 代码。
像这样:
eval(response.bar)
鉴于:
response = {foo: "some value", bar:"function(){console.log(this);}"}
不要使用 eval — 它既不安全又棘手。用引号包裹你的函数体,从那里删除关键字函数,然后在客户端使用函数构造函数创建新函数。
JSON:
{
"fn": "alert(arguments);"
}
客户端解析代码:
var myFunction = new Function(JSON.parse(jsonString).fn);
这样更好,因为您的函数不会自动执行任何代码或将自身暴露给全局上下文。
唯一相当大的不便之处是没有参数列表。您必须改用 arguments
对象。
我想从服务器给出这样的响应:
{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);}"}
在服务器端使用这个:
render json: {foo: "some value", bar: 'function(){console.log(this);}'}
现在您可以 post 处理已解析的 JSON:
json.bar = eval(json.bar);
服务器将始终return您的 JS 代码部分的字符串值。
但是您可以使用 eval
函数的 JS 代码。
像这样:
eval(response.bar)
鉴于:
response = {foo: "some value", bar:"function(){console.log(this);}"}
不要使用 eval — 它既不安全又棘手。用引号包裹你的函数体,从那里删除关键字函数,然后在客户端使用函数构造函数创建新函数。
JSON:
{
"fn": "alert(arguments);"
}
客户端解析代码:
var myFunction = new Function(JSON.parse(jsonString).fn);
这样更好,因为您的函数不会自动执行任何代码或将自身暴露给全局上下文。
唯一相当大的不便之处是没有参数列表。您必须改用 arguments
对象。