Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 活动模型序列化程序与JSONP一起工作吗?_Ruby On Rails_Ruby On Rails 4_Active Model Serializers - Fatal编程技术网

Ruby on rails 活动模型序列化程序与JSONP一起工作吗?

Ruby on rails 活动模型序列化程序与JSONP一起工作吗?,ruby-on-rails,ruby-on-rails-4,active-model-serializers,Ruby On Rails,Ruby On Rails 4,Active Model Serializers,如果没有,我如何使它与我的AJAX请求兼容 编辑:看起来我不清楚我想要实现什么。比如说,我有一个Post类,它包含id、author、tags和content等属性。现在,我将使用以下ActiveModel::Serializer对JSON响应进行编码: class PostSerializer < ActiveModel::Serializer attributes :id, :author, :tags, :content, end 生成如下所示的JSON文件 { "post

如果没有,我如何使它与我的AJAX请求兼容

编辑:看起来我不清楚我想要实现什么。比如说,我有一个Post类,它包含id、author、tags和content等属性。现在,我将使用以下ActiveModel::Serializer对JSON响应进行编码:

class PostSerializer < ActiveModel::Serializer
  attributes :id, :author, :tags, :content,
end
生成如下所示的JSON文件

{
  "posts": [
    {
      "id": 1,
      "author": "John Doe",
      "tags": "test",
      "content": "Hello world"
    }
  ]
}
现在我的目标是使用JSONP,这样当有人在请求中传入jsoncallback参数(例如GET'/posts?jsoncallback=callback_function')时,我将能够生成以下内容:

callback_function({
  "posts": [
    {
      "id": 1,
      "author": "John Doe",
      "tags": "test",
      "content": "Hello world"
    }
  ]
})
<% if params[:jsoncallback].blank? %>
<%= @posts_json.html_safe %>
<% else %>
<%= params[:jsoncallback] %>(<%= @posts_json.html_safe %>)
<% end %>
目前,我在Post对象上使用to_json并将结果存储到名为@posts_json的变量中,然后在控制器中将内容类型指定为text/javascript,并呈现一个html.erb文件,如下所示:

callback_function({
  "posts": [
    {
      "id": 1,
      "author": "John Doe",
      "tags": "test",
      "content": "Hello world"
    }
  ]
})
<% if params[:jsoncallback].blank? %>
<%= @posts_json.html_safe %>
<% else %>
<%= params[:jsoncallback] %>(<%= @posts_json.html_safe %>)
<% end %>

()
我相信您会同意,这个解决方案非常难看,问题是,由于我在控制器中使用的to_json方法,它开始给我带来问题


因此,我希望使用ActiveModel::Serializer获得相同的功能。我该怎么做呢?

显然在普通Rails中,
render
语法已经处理了回调。只需将callback:params[:jsoncallback]作为选项传入即可


单击并浏览呈现JSON部分下的文档。

让我们看看一些代码…@Severin Done。。。我希望AMS有一个选项,我可以做一些类似于
render json:@post,jsonp:callback_function