简体   繁体   中英

Using HTTP PUT to send JSON with Jquery and Rails 3

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.

Example:

$.ajax({
    url: window.location.pathname,
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({_method:'PUT', page:{my_data: 1}),
    dataType: 'json'
});

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.

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");
    }
});

Is setting the HTTP override header the best way?

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'
});

Also make sure you are respecting the same origin policy or jquery might try to use JSONP which works only with GET verbs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM