使用HTTP PUT发送JSON与jQuery和Rails 3 [英] Using HTTP PUT to send JSON with Jquery and Rails 3
问题描述
HTTP PUT并不完全是跨浏览器,滑轨(我用Rails 3)支持使用POST并通过 _method
查询参数。这是伟大的,但它似乎并没有发送JSON何时工作。
HTTP PUT isn't entirely cross browser so Rails (I'm using Rails 3) supports using POST and passing the _method
query param. This is great, but it doesn't seem to work when sending JSON.
示例:
$.ajax({
url: window.location.pathname,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({_method:'PUT', page:{my_data: 1}),
dataType: 'json'
});
在Rails的看到这一点,不承认_method'覆盖,因为它是通过JSON格式(也许是转换后的?)。 Rails的返回一个错误,没有路由匹配...说,它不能找到路线(到资源),我想是因为它不符合REST更新= HTTP PUT动词,我甚至试过追加这网址:<?code> _方法= PUT ,但得到了同样的结果。
When Rails sees this, it doesn't recognize the '_method' override because it's passed in the JSON format (perhaps that conversion is later?). Rails returns an error "No route matches ..." saying it can't find the route (to the resource), I assume because it doesn't match the REST update=HTTP PUT verb, I've even tried appending this to the URL: ?_method=PUT
but got the same result.
这的的唯一的事情确实的似乎工作是设置一个HTTP标头:
The only thing that does seem to work is setting an HTTP header:
$.ajax({
url: window.location.pathname,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({my_data: 1}),
dataType: 'json',
beforeSend: function(xhr){
xhr.setRequestHeader("X-Http-Method-Override","put");
}
});
是设置HTTP头覆盖的最好方法是什么?
推荐答案
AJAX支持 PUT
动词直接何必与困扰 _method
和自定义HTTP标头:
AJAX supports the PUT
verb directly so why bothering with _method
and custom HTTP headers:
$.ajax({
url: window.location.pathname,
type: 'PUT',
contentType: 'application/json',
data: JSON.stringify({ page: { my_data: 1 }),
dataType: 'json'
});
另外,还要确保你的尊重同源策略或jQuery的可能会尝试使用JSONP仅<$其中工程C $ C> GET 动词。
Also make sure you are respecting the same origin policy or jquery might try to use JSONP which works only with GET
verbs.
这篇关于使用HTTP PUT发送JSON与jQuery和Rails 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!