开发者

Should PUT and DELETE be used in forms?

开发者 https://www.devze.com 2023-02-14 11:08 出处:网络
Assuming my web application has full support of PUT and DELETE on the server side, should I make use of them?

Assuming my web application has full support of PUT and DELETE on the server side, should I make use of them?

Basically my question is how many browsers support this:

<form method="PUT">

or

<form method="DELETE">

Is there any benefits to using these two HTTP Methods other than being REST-compliant? (assuming the replacement for these 开发者_StackOverflow中文版two methods is the commonly used POST)


Your question involves two closely related but separate standards, HTTP and HTML. The PUT and DELETE methods are part of HTTP. In HTTP they have obvious use in RESTful interfaces, and other services which build on HTTP such as Webdav.

HTML up to version 4 only defines the use of POST and GET for forms. HTML5 at this time appears as though it may support the further methods. [note, support is not included in the current w3 draft]

Any current browser support (I'm not directly aware of any) will be very limited and only really useful as an experiment at the bleeding edge.


GET, POST, PUT and DELETE (there are others) are a part of the HTTP standard, but you are limited to GET and POST in HTML forms at this time.

As Andrew mentioned, you can use PUT and DELETE in AJAX requests; however, this only works in some browsers (see http://api.jquery.com/jQuery.ajax/).


No, GET & POST are the only valid HTTP method values for the method attribute. See the HTML spec for more information.

I believe you can use them in AJAX requests, though.


As of February 2023, latest HTML specs and drafts still don't have support for methods other than GET and POST by default. If you don't use a method middleware, you are stuck with these two options. (method attribute can also have 'dialog' as a value, but it is irrelevant since it is not directly related to HTTP methods.)

https://html.spec.whatwg.org/#attr-fs-method


It's not really possible to send a DELETE request using <form />, but you can send one to the one API endpoint and redirect the user to another page. This will simulate the desired behaviour. The code with jQuery is provided.

$(".control-action").on("click", () => {
  alert("Click");

  $.ajax({
    // call a DELETE endpoint of API
    url: "/api/items/5",
    method: "DELETE",
    headers: {
      "X-Api-Key": "363463822036d927c733d5607af109e2"
    },
    success : function () {
      // redirect to another page
      // window.location.href = "/items";
    }
  });
});
.link {
  text-decoration: underline;
  cursor: pointer;
  color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<span class="link control-action">Call action</span>

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号