在Rails应用中输出jSON [英] Outputting jSON in a rails app

查看:69
本文介绍了在Rails应用中输出jSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,这里有3位新开发人员.

ok, rails 3 new developer here.

我希望我的jquery能够从Rails 3应用程序中获取项目的json对象.这是我的控制器.

I want my jquery to be able to get a json object from the rails 3 application for projects. Here is my controller.

def yourprojects
  @projects = Projects.all(current_user)

  respond_to do |format|
    format.html # index.html.erb
    format.json  { render :json => @projects }
  end
end

我在jquery中添加了format.json行...

I added the format.json line... in jquery i have:

$.ajax({url: '/projects/yourprojects', dataType: 'json'});

所以我认为应该可以.相反,服务器将返回:缺少模板"缺少模板""{,locale => [:en,:en],:handlers => [:rjs,:rhtml,:builder,:rxml,: erb],在视图路径中:formats => [:html]}"

So that should work i thought. Instead the server is returning: "Template is missing" "Missing template ,,,, with {:locale=>[:en, :en], :handlers=>[:rjs, :rhtml, :builder, :rxml, :erb], :formats=>[:html]} in view paths"

您需要jsOn返回的模板吗? Rails 3应用程序不应该知道如何格式化json吗?

do you need a template for a jsOn return? shouldn't the rails 3 app know how to format the json?

路由文件:

resources :projects do
    collection do
        get 'yourprojects'  
    end
end

推荐答案

您可以为真正的REST设置Accept: application/json标头,也可以将格式添加到URL中以进行快速黑客攻击:

You can set the Accept: application/json header for real REST, or you can add the format to the URL for quick hackery:

$.ajax({url: '/projects/yourprojects.json', dataType: 'json'});

这篇关于在Rails应用中输出jSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆