我正在尝试向我的Rails 3应用程序发出一个简单的PUT JSON请求:
$.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
我做错了什么?
答案 0 :(得分:1)
我犯了两个错误。首先,contentType
必须设置为application/json
,而不仅仅是json
。其次,data
必须使用JSON.stringify({...})
手动序列化。