[英]Outputting jSON in a rails app
ok, rails 3 new developer here. 好的,rails 3新开发者在这里。
I want my jquery to be able to get a json object from the rails 3 application for projects. 我希望我的jquery能够从rails 3应用程序中获取项目的json对象。 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
I added the format.json line... in jquery i have: 我在jquery中添加了format.json行...我有:
$.ajax({url: '/projects/yourprojects', dataType: 'json'});
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"
而是服务器返回:“模板丢失”“缺少模板,,,,带{:locale => [:en,:en] ,: handlers => [:rjs,:rhtml,:builder,:rxml,: erb],:formats => [:html]}在视图路径中“
do you need a template for a jsOn return? 你需要一个jsOn回归的模板吗? shouldn't the rails 3 app know how to format the json?
rails 3 app应该不知道如何格式化json?
Routes File: 路线文件:
resources :projects do
collection do
get 'yourprojects'
end
end
您可以为真实REST设置Accept: application/json
标头,或者您可以将格式添加到URL以便快速解决:
$.ajax({url: '/projects/yourprojects.json', dataType: 'json'});
This is not issue of Rails but rather AJAX / jQuery not sending Accept header: Try this: 这不是Rails的问题,而是AJAX / jQuery不发送Accept标头:试试这个:
$.ajax({
url: 'url_to_action', dataType: "json",
beforeSend : function(xhr){
xhr.setRequestHeader("Accept", "application/json")
},
success : function(data){
//.. do something with data
},
error: function(objAJAXRequest, strError, errorThrown){
alert("ERROR: " + strError);
}
}
);
If all your AJAX requests expect JSON, then you can set header globally: 如果您的所有AJAX请求都需要JSON,那么您可以全局设置标头:
$.ajaxSetup({
dataType: 'json',
'beforeSend' : function(xhr){
xhr.setRequestHeader("Accept", "application/json")
}
});
Other option would be adding .json
to path or data:{format: 'json'}
to $.ajax
hash of options. 其他选项是将
.json
添加到路径或data:{format: 'json'}
到选项的$.ajax
哈希。 Rails supports format path suffixes by default for resoures
routing. Rails默认支持格式路径后缀,用于
resoures
路由。 Just try rake routes
to see. 试试看
rake routes
。
:formats=>[:html]
That says the server is thinking that html
is being requested. 这说服务器认为正在请求
html
。 Try adding a .json
to your path (and possible route) and that will force the format. 尝试将
.json
添加到您的路径(和可能的路径),这将强制格式化。 TO make that would would need a route something like this: 要做到这将需要一个像这样的路线:
map.your_projects '/projects/yourprojects.:format',
:controller => 'projects',
:action => 'yourprojects'
Somehow, someway, the params[:format]
should be "json"
for this request so the format handlers can do the right thing. 不知怎的,某种程度上,对于这个请求,
params[:format]
应该是"json"
,因此格式处理程序可以做正确的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.