0

我的应用程序应该通过 json 发送结构,这些功能可以正常工作:

function send_json()
{
    var formData = form2object('myForm');
    var json_data = JSON.stringify(formData, null, '\t');
    $.post("", json_data);
}

它创建 json_data 并通过邮寄方式发送。但我不明白如何在另一边捕捉这些数据,你能帮我吗?我应该采用这种结构并对其进行一些操作。

当我发送数据时,我得到了 json:

{ "type": "test", "ttl": "1", "amount": "1", "rules": { "rule1": "1", "value1": "4444", "stackcount1": "1", "rule2": "2", "value2": "333", "stackcount2": "2" }}

在控制器中我写了这个:

class AdminController < ApplicationController
  def index
    @json_string = params[:amount]
    if !@json_sting.nil?
      @json_string = JSON.parse(params[:amount])
    end
  end
end

在视图(haml)中,我写道:

=@json_string

它不起作用!

但是wireshark显示:

POST /admin/ HTTP/1.1
Host: localhost:3000
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:14.0) Gecko/20100101 Firefox/14.0.1
Accept: */*
Accept-Language: ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://localhost:3000/admin/
Content-Length: 192
Cookie: _GiftSenderTool_session=BAh7BzoQX2NzcmZfdG9rZW4iMTVyNVJCMTBvcGpKSk5OcFN4bW15YVlpRlF1TUNtb1gwZkY0bTRuRHlsNnM9Ig9zZXNzaW9uX2lkIiU4ZjFjNTNjNTY0MTQ1MGExNmFiODcxZGEyYzU5ZTkxMg%3D%3D--f21bf3b96edc3bc551c8de68acc6da17685d58b4
Pragma: no-cache
Cache-Control: no-cache

{
."type": "test",
."ttl": "1",
."amount": "1",
."rules": {
.."rule1": "1",
.."value1": "4444",
.."stackcount1": "1"
.},
."authenticity_token": "n3B6D/Km9zOgOzlosK/OLHyTCDLk3MyCTlTBinfQcnY="
}

这意味着我无法获取数据。

4

1 回答 1

1

您必须在某些 rails 控制器操作中捕获您的 JSON 对象。如果您的 JSON 字符串如下所示:

{ "user": { "id": 1, "name": "Tom" } }

然后这样做:

require "json"
...
def some_action
  user = JSON.parse(params[:user])
  puts "User id is #{user[:id]}"
  ...
end
于 2012-08-10T14:32:46.437 回答