如何在rails中获取JSON ajax请求的数据?
问题描述:
我试图做一个简单的PUT JSON要求我的Rails应用程序3:如何在rails中获取JSON ajax请求的数据?
$.ajax({type: 'PUT', url: '/controlpanel/custom_forms/1', data: { hello: 'world' }, contentType: 'json'})
不知何故,该数据不接收params
只包含ID。下面是在服务器端:
Started PUT "/controlpanel/custom_forms/1" for 127.0.0.1 at 2012-05-22 23:05:25 -0400
Processing by Controlpanel::CustomFormsController#update as */*
Parameters: {"id"=>"1"}
我期待Parameters
是{"id"=>"1", "hello"=>"world"}
请求看起来很好,在Chrome:
请求头
PUT /controlpanel/custom_forms/1 HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Content-Length: 11
Origin: localhost:3000
X-CSRF-Token: HgGPJmgf0iXlsHtmZrifqFoww/rlzq+hAKb63HbAl8g=
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46 Safari/536.5
Content-Type: json
Accept: */*
Referer: http://localhost:3000/controlpanel/custom_forms/1/edit?feature_id=1
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: user_credentials=whatever
请求负载
hello=world
我在做什么错?
答
我犯了两个错误。首先,contentType
必须设置为application/json
,而不仅仅是json
。其次,data
必须手动序列化与JSON.stringify({...})
。