How to specify DELETE method in a link or form?

大城市里の小女人 提交于 2019-11-30 16:50:46
Paul D. Waite

You certainly can’t create a link that uses anything other than GET. Since HTML began, links have been meant to be idempotent and free from side effects.

For forms and XMLHTTPRequests, Caps’ link is the place to look: Are the PUT, DELETE, HEAD, etc methods available in most web browsers?.

Was trying to figure this out for a rails app that was using Angular on the front end; these seems to work for that environment:

<a data-confirm="Are you sure?" data-method="delete" href="/link-to-resource" rel="nofollow">Delete</a>

Edit: Just to give everyone a heads up, I think you still need to have jQuery for this to work. I removed jQuery and it stopped working; I put it back and it started working.

Adam Sanderson

By default, not there is no way to do this. Links always perform GETs, forms can use GETs or POSTs.

That said, with a little JavaScript, it's possible. Rails for instance ships with helpers which will add a data-method attribute to links. Rails-UJS is a jQuery library that will transparently intercept clicks on these links, and trigger a form submit with a _method parameter used for overriding the normal HTTP method. Finally Rack will intercept requests with a _method params, and overwrite the request method with the value in _method.

Other frameworks no doubt follow a similar pattern.

If you want even more details, I've written up an explanation of how Rails, Rails-UJS, and Rack all work together to provide this.

It's good to know how your libraries work.

It is not possible to create a link or form with delete method.

Many web framework create a hidden input called "_method" for handling PUT and DELETE.

I created a plugin for automatically convert links to forms : RestfulizerJs

You can take a look here : https://github.com/Ifnot/RestfulizerJs

@Ifnot plugin is great but I created a one based on $.ajax function instead of appending hidden forms! here's a simple example for a DELETE request

HTML

<button class="delete" data-target="http://example.com/post/post-id/" data-method="DELETE" data-disabled="true">Delete Article</button>

JavaScript

$(".delete").restintag(optionsObj, function(data) {
    console.log(data);
},
function(error) {
    console.log(error);
});

https://github.com/KhaledElAnsari/RESTInTag/

just add a data-method attribute,<a data-method='put' href='whatever'>link</a>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!