英文:
Extracting the actual POST parameters from a Rails request
问题
为什么 request_parameters()
方法包括了冗余的嵌套参数集?
英文:
I'm trying to parse the POST params out of an AJAX form submission in Rails, but for some reason it keeps on including a nested, duplicate version of the parameters, and I'm not sure why.
AJAX:
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify({foo:'bar',timestamp:Date.now()}),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
RAILS:
class TestController < ApplicationController
def post_test
puts "RAW POST: #{request.raw_post}"
puts "POST PARAMS: #{request.request_parameters().to_json}"
end
end
RESULT:
> RAW POST: {"foo":"bar","timestamp":1690813226909}
> POST PARAMS: {"foo":"bar","timestamp":1690813226909,"test":{"foo":"bar","timestamp":1690813226909}}
Why is the request_parameters()
method including the redundant nested set of parameters?
答案1
得分: 2
几乎可以肯定是因为您已经配置了 wrap_parameters。
更新
嗯,看起来在 Rails 7 中现在已经自动完成了,即使没有配置 wrap_parameters
。
英文:
Almost certainly because you have wrap_parameters configured.
Update
Hmm, looks like that's done automatically now in Rails 7, even without wrap_parameters
configured.
答案2
得分: 0
阅读jQuery上的Ajax文档:https://api.jquery.com/jquery.ajax/,您可以将对象、字符串或数组传递给数据参数。
$.ajax({
type: 'POST',
url: url,
data: { foo: 'bar', timestamp: Date.now() },
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
通过这种方式,您可以发送一个完整的对象而无需解析为字符串,并在Rails中以以下方式接收它:
class TestController < ApplicationController
def post_test
puts "All data: #{params}"
end
end
备注:对不起,我的英语不太好。
英文:
Reading de docs of Ajax on Jquery: https://api.jquery.com/jquery.ajax/ you can pass objects, strings, or arrays to the data argument
$.ajax({
type: 'POST',
url: url,
data: { foo:'bar', timestamp:Date.now() },
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
In this way you can send a complete object without parsing to string and receive it on rails in the following way:
class TestController < ApplicationController
def post_test
puts "All data: #{params}"
end
end
PD: Sorry for my poor English
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论