在 HTML 表单中使用 PUT 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8054165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:25:36  来源:igfitidea点击:

Using PUT method in HTML form

htmlformshttp

提问by MyTitle

Can I use a PUT method in an HTML form to send data from the form to a server?

我可以在 HTML 表单中使用 PUT 方法将数据从表单发送到服务器吗?

采纳答案by dqhendricks

XHTML 1.x forms only support GET and POST. GET and POST are the only allowed values for the "method" attribute.

XHTML 1.x 表单仅支持 GET 和 POST。GET 和 POST 是“method”属性唯一允许的值。

回答by phihag

According to the HTML standard, you can not. The only valid values for the method attribute are getand post, corresponding to the GET and POST HTTP methods. <form method="put">is invalid HTML and will be treated like <form>, i.e. send a GET request.

根据HTML 标准,您不能。method 属性的唯一有效值是getand post,对应于 GET 和 POST HTTP 方法。<form method="put">是无效的 HTML,将被视为<form>,即发送 GET 请求。

Instead, many frameworks simply use a POST parameter to tunnel the HTTP method:

相反,许多框架只是使用 POST 参数来隧道传输 HTTP 方法:

<form method="post" ...>
  <input type="hidden" name="_method" value="put" />
...

Of course, this requires server-side unwrapping.

当然,这需要服务器端解包。

回答by hakre

Can I use "Put" method in html form to send data from HTML Form to server?

我可以在 html 表单中使用“Put”方法将数据从 HTML 表单发送到服务器吗?

Yes you can, but keep in mind that it will not result in a PUT but a GET request. If you use an invalid value for the methodattribute of the <form>tag, the browser will use the default value get.

是的,您可以,但请记住,它不会导致 PUT 而是 GET 请求。如果标签的method属性使用无效值<form>,浏览器将使用默认值get

HTML forms (up to HTML version 4 (, 5 Draft) and XHTML 1) only support GET and POST as HTTP request methods. A workaround for this is to tunnel other methods through POST by using a hidden form field which is read by the server and the request dispatched accordingly. XHTML 2.0once planned to support GET, POST, PUT and DELETE for forms, but it's going into XHTML5of HTML5, which does not plan to support PUT. [update to]

HTML 表单(直到 HTML 版本 4(、5 Draft)和 XHTML 1)仅支持 GET 和 POST 作为 HTTP 请求方法。一种解决方法是通过使用隐藏的表单字段通过 POST 隧道传输其他方法,该字段由服务器读取并相应地分派请求。XHTML 2.0曾计划支持GET,POST,PUT和DELETE的形式,但它进入XHTML5HTML5,它不打算支持PUT。[更新到]

You can alternatively offer a form, but instead of submitting it, create and fire a XMLHttpRequest using the PUT method with JavaScript.

您也可以提供一个表单,但不是提交表单,而是使用 JavaScript 的 PUT 方法创建和触发 XMLHttpRequest。

回答by Tofeeq

Unfortunately, modern browsers do not provide native support for HTTP PUT requests. To work around this limitation, ensure your HTML form's method attribute is “post”, then add a method override parameter to your HTML form like this:

不幸的是,现代浏览器不提供对 HTTP PUT 请求的原生支持。要解决此限制,请确保您的 HTML 表单的方法属性为“post”,然后向您的 HTML 表单添加一个方法覆盖参数,如下所示:

<input type="hidden" name="_METHOD" value="PUT"/>

To test your requests you can use "Postman" a google chrome extension

要测试您的请求,您可以使用“邮递员”谷歌浏览器扩展

回答by Enrique René

To set methods PUT and DELETE I perform as following:

要设置方法 PUT 和 DELETE 我执行如下:

<form
  method="PUT"
  action="domain/route/param?query=value"
>
  <input type="hidden" name="delete_id" value="1" />
  <input type="hidden" name="put_id" value="1" />
  <input type="text" name="put_name" value="content_or_not" />
  <div>
    <button name="update_data">Save changes</button>
    <button name="remove_data">Remove</button>
  </div>
</form>
<hr>
<form
  method="DELETE"
  action="domain/route/param?query=value"
>
  <input type="hidden" name="delete_id" value="1" />
  <input type="text" name="delete_name" value="content_or_not" />
  <button name="delete_data">Remove item</button>
</form>

Then JS acts to perform the desired methods:

然后 JS 执行所需的方法:

<script>
   var putMethod = ( event ) => {
     // Prevent redirection of Form Click
     event.preventDefault();
     var target = event.target;
     while ( target.tagName != "FORM" ) {
       target = target.parentElement;
     } // While the target is not te FORM tag, it looks for the parent element
     // The action attribute provides the request URL
     var url = target.getAttribute( "action" );

     // Collect Form Data by prefix "put_" on name attribute
     var bodyForm = target.querySelectorAll( "[name^=put_]");
     var body = {};
     bodyForm.forEach( element => {
       // I used split to separate prefix from worth name attribute
       var nameArray = element.getAttribute( "name" ).split( "_" );
       var name = nameArray[ nameArray.length - 1 ];
       if ( element.tagName != "TEXTAREA" ) {
         var value = element.getAttribute( "value" );
       } else {
       // if element is textarea, value attribute may return null or undefined
         var value = element.innerHTML;
       }
       // all elements with name="put_*" has value registered in body object
       body[ name ] = value;
     } );
     var xhr = new XMLHttpRequest();
     xhr.open( "PUT", url );
     xhr.setRequestHeader( "Content-Type", "application/json" );
     xhr.onload = () => {
       if ( xhr.status === 200 ) {
       // reload() uses cache, reload( true ) force no-cache. I reload the page to make "redirects normal effect" of HTML form when submit. You can manipulate DOM instead.
         location.reload( true );
       } else {
         console.log( xhr.status, xhr.responseText );
       }
     }
     xhr.send( body );
   }

   var deleteMethod = ( event ) => {
     event.preventDefault();
     var confirm = window.confirm( "Certeza em deletar este conteúdo?" );
     if ( confirm ) {
       var target = event.target;
       while ( target.tagName != "FORM" ) {
         target = target.parentElement;
       }
       var url = target.getAttribute( "action" );
       var xhr = new XMLHttpRequest();
       xhr.open( "DELETE", url );
       xhr.setRequestHeader( "Content-Type", "application/json" );
       xhr.onload = () => {
         if ( xhr.status === 200 ) {
           location.reload( true );
           console.log( xhr.responseText );
         } else {
           console.log( xhr.status, xhr.responseText );
         }
       }
       xhr.send();
     }
   }
</script>

With these functions defined, I add a event listener to the buttons which make the form method request:

定义了这些函数后,我向发出表单方法请求的按钮添加了一个事件侦听器:

<script>
  document.querySelectorAll( "[name=update_data], [name=delete_data]" ).forEach( element => {
    var button = element;
    var form = element;
    while ( form.tagName != "FORM" ) {
      form = form.parentElement;
    }
    var method = form.getAttribute( "method" );
    if ( method == "PUT" ) {
      button.addEventListener( "click", putMethod );
    }
    if ( method == "DELETE" ) {
      button.addEventListener( "click", deleteMethod );
    }
  } );
</script>

And for the remove button on the PUT form:

对于 PUT 表单上的删除按钮:

<script>
  document.querySelectorAll( "[name=remove_data]" ).forEach( element => {
    var button = element;
    button.addEventListener( "click", deleteMethod );
</script>

_ - - - - - - - - - - -

_ - - - - - - - - - - -

This article https://blog.garstasio.com/you-dont-need-jquery/ajax/helps me a lot!

这篇文章https://blog.garstasio.com/you-dont-need-jquery/ajax/对我帮助很大!

Beyond this, you can set postMethod function and getMethod to handle POST and GET submit methods as you like instead browser default behavior. You can do whatever you want instead use location.reload(), like show message of successful changes or successful deletion.

除此之外,您可以设置 postMethod 函数和 getMethod 来处理 POST 和 GET 提交方法,而不是浏览器的默认行为。你可以做任何你想做的事情location.reload(),比如显示成功更改或成功删除的消息。

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

JSFiddle: https://jsfiddle.net/enriquerene/d6jvw52t/53/

JSFiddle:https://jsfiddle.net/enriquerene/d6jvw52t/53/