在 Rails 应用程序中输出 JSON

2024-04-05

好的,Rails 3 新开发人员在这里。

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

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 行...我有:

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

所以我想这应该可行。相反,服务器返回:“模板丢失”“缺少模板 , with {:locale=>[:en, :en], :handlers=>[:rjs, :rhtml, :builder, :rxml, : erb], :formats=>[:html]} 在视图路径中”

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

路线文件:

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

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

$.ajax({url: '/projects/yourprojects.json', dataType: 'json'});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Rails 应用程序中输出 JSON 的相关文章

随机推荐