从Rails请求中提取实际的POST参数

huangapple go评论55阅读模式
英文:

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: &#39;POST&#39;,
  url: url,
  data: { foo:&#39;bar&#39;, timestamp:Date.now() },
  dataType: &#39;json&#39;,
  contentType: &#39;application/json; charset=utf-8&#39;
});

In this way you can send a complete object without parsing to string and receive it on rails in the following way:

class TestController &lt; ApplicationController

  def post_test
    puts &quot;All data: #{params}&quot;
  end

end

PD: Sorry for my poor English

huangapple
  • 本文由 发表于 2023年7月31日 22:25:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76804564.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定