Ruby on rails 来自url的Rails6上带有查询的Json响应
仅在Rails 6上,当: 我在url如下的页面上收到json响应:Ruby on rails 来自url的Rails6上带有查询的Json响应,ruby-on-rails,Ruby On Rails,仅在Rails 6上,当: 我在url如下的页面上收到json响应: www.site.com/foo 当url类似于: www.site.com/foo?q=x 复制: rails新待办事项 rails脚手架待办事项任务:字符串 rails数据库:迁移 rails服务器 创建任务 在文件show.json.jbuilder中,您将看到: json.partial!“todo/todo”,todo:@todo 转到显示页面(todo/1) 在浏览器控制台上键入se json响应: $.aja
www.site.com/foo
当url类似于:
www.site.com/foo?q=x
复制:
Started GET "/todos/1.json" for ::1 at 2019-10-28 13:55:54 -0300
Processing by TodosController#show as JSON
Parameters: {"id"=>"1"}
Todo Load (0.3ms) SELECT "todos".* FROM "todos" WHERE "todos"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/controllers/todos_controller.rb:67:in `set_todo'
Rendering todos/show.json.jbuilder
Rendered todos/_todo.json.jbuilder (Duration: 1.0ms | Allocations: 125)
Rendered todos/show.json.jbuilder (Duration: 2.2ms | Allocations: 306)
Completed 200 OK in 10ms (Views: 3.9ms | ActiveRecord: 0.3ms | Allocations: 1565)
但如果您的url为“todo/1?q=foo”,则您没有数据:
Started GET "/todos/1?q=foo.json" for ::1 at 2019-10-28 13:55:44 -0300
Processing by TodosController#show as JSON
Parameters: {"q"=>"foo.json", "id"=>"1"}
Todo Load (0.2ms) SELECT "todos".* FROM "todos" WHERE "todos"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/controllers/todos_controller.rb:67:in `set_todo'
Rendering todos/show.html.erb within layouts/application
Rendered todos/show.html.erb within layouts/application (Duration: 0.7ms | Allocations: 89)
Completed 200 OK in 25ms (Views: 21.3ms | ActiveRecord: 0.2ms | Allocations: 6547)
Obs:我打开了此这是因为请求必须采用以下格式:
www.site.com/foo.json?q=x
如果要向请求传递参数,可以使用ajax的data
参数
例如:
$.ajax({
url: "/todos",
type: "GET",
data: {
id: 1,
q: "x"
},
success: function (response) {
console.log(response.data)
}
})
为了在rails 6.0.0中工作,我们需要明确告知在url有查询时使用json格式: todos\u controller.rb 更改为:
def show
end
致:
嗨,Samy Kacimi,我试过这个,但没有改变。我还更新了这个问题,因为这个行为只出现在rails 6上,rails服务器的日志在发出请求时说了什么?好问题。我用这些信息更新了上面的帖子。我们可以看到jbuilder并没有在其中一个版本中编译
def show
respond_to do |format|
format.html
format.json
end
end