Ruby-on-rails 如何从 rails 中的 respond_to 方法生成 json?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2566759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:29:08  来源:igfitidea点击:

how can I generate json from respond_to method in rails?

ruby-on-railsjsonrespond-to

提问by Oberon Dude

If I have a block of code like this:

如果我有这样的代码块:

def show
  @post = Post.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @post }
    end
  end

How do I add something like

我如何添加类似的东西

format.json

Any tips, pointers, ideas gladly welcomed...

很高兴欢迎任何提示、指示、想法......

回答by rogeriopvl

It's just like the other formats except that you use render :jsoninstead.

它就像其他格式一样,只是您render :json改用了。

respond_to do |format|
  format.html # show.html.erb
  format.xml  { render :xml => @post }
  format.json { render :json => @post }
end

回答by VP.

or you can handle it as javascript

或者您可以将其作为 javascript 处理

respond_to do |format|
  format.js { render :json { :only => :name }.to_json }
end

then you just access your action with ".js" in the end.

那么你最后只需要使用“.js”来访问你的动作。