How do you send a request with the “DELETE” HTTP verb?

后端 未结 4 1161
温柔的废话
温柔的废话 2020-12-29 00:09

I\'d like to create a link in a view within a Rails application that does this...

DELETE /sessions

How would I do that.

Added compl

相关标签:
4条回答
  • 2020-12-29 00:30

    I don't know about Rails specifically, but I frequently build web pages which send DELETE (and PUT) requests, using Javascript. I just use XmlHttpRequest objects to send the request.

    For example, if you use jQuery:

    have a link that looks like this:

    <a class="delete" href="/path/to/my/resource">delete</a>
    

    And run this Javascript:

    $(function(){
        $('a.delete').click(function(){
            $.ajax(
                {
                    url: this.getAttribute('href'),
                    type: 'DELETE',
                    async: false,
                    complete: function(response, status) {
                        if (status == 'success')
                            alert('success!')
                        else
                            alert('Error: the service responded with: ' + response.status + '\n' + response.responseText)
                    }
                }
            )
            return false
        })
    })
    

    I wrote this example mostly from memory, but I'm pretty sure it'll work....

    0 讨论(0)
  • 2020-12-29 00:37

    Rails' built in method for links will generate something like this:

    <a href="/sessions?method=delete" rel="nofollow">Logout</a>
    

    If you don't want to use the Rails' built in method (i.e. don't want the rel="nofollow", which prevents search engine crawlers from following the link), you can also manually write the link and add the data-method attribute, like so:

    <a href="/sessions" data-method="delete">Logout</a>
    

    Browsers can only send GET/POST requests, so this will send a normal GET request to your Rails server. Rails will interpret and route this as a DESTROY/DELETE request, and calls the appropriate action.

    0 讨论(0)
  • 2020-12-29 00:40

    Correct, browsers don't actually support sending delete requests. The accepted convention of many web frameworks is to send a _method parameter set to 'DELETE', and use a POST request.

    Here's an example in Rails:

    <%= link_to 'log out', session_path, :method => :delete %>
    

    You may want to have a look at Restful Authentication.

    0 讨论(0)
  • 2020-12-29 00:47

    Correct me if I'm wrong, but I believe you can only send POST and GET requests with a browser (in HTML).

    0 讨论(0)
提交回复
热议问题