Doing a HTTP PUT from a browser

2019-01-08 22:01发布

问题:

I would like to know what the definitive (?) answer is for how to do things other then POST/GET from a browser - either a HTML form or Ajax, as I hear mixed reports on what browsers allow what (specifically on the ajax side).

When building a back end in RESTful style it is nice to use proper verbs like PUT, HEAD, OPTIONS etc... in rails, a hidden form field called method (IIRC?) is used to simulate this, and at the back end the dispatch to the appropriate controller for the verb. Is this now (in late 2009) necessary? what are the conventions?

回答1:

It seems that most browsers don't support other methods besides GET and POST since it is a limitation of HTML forms. Here's another question on the topic:

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

In order to simulate the PUT, DELETE, etc. methods, you could add a hidden input to a regular GET/POST form with the pseudo-method and have your application translate it so that your controllers see it as if it were a true PUT request, as you mentioned. I've seen this method used in google sitebricks (in java - sorry I don't have any rails-specific reference, but this might at least give you an idea) in this code. I think this is probably the method we are stuck with until something in HTML spec changes (and the browsers with it)

However, GET, POST, PUT and DELETE are supported in AJAX by the major browsers, so there should be no need for a hidden input if you aren't relying on the HTML form.



回答2:

You have to use AJAX to do anything other than GETs and POSTs, I would recommend the jQuery Forms plugin to allow you to submit a form as a PUT.



回答3:

HTTP has 4 GET,POST,PUT,UPDATE. But most browser support only GET and POST. PUT and UPDATE are simulated by sending additional parameters in request. In rails it's _method="PUT" or _method="UPDATE".



回答4:

I believe the preferred solution to this problem is to use the X-HTTP-Method-Override header. If you search on this term you should find plenty of examples of how to use it.



回答5:

I think you'll find many firewalls block some of the cooler HTTP verbs. So while it may work for you, if you're trying to create something for the general public consumed from corporate sites, you'll probably want to stick with the basics.



回答6:

Besides ajax generated requests, another way of getting these additional methods is with a webdav client. filesystem clients exist for all major operationg systems, and there are some additional clients that can support it for web authoring.

For instance, the Amaya web browser allows you to edit documents on the web and save them directly to the server, using the PUT method. There are plugins for this on other browsers and several web graphical editors, such as Dreamweaver also support WebDAV.

WebDAV also supports a number of other methods besides the methods defined in HTTP1.1 for its own use.



标签: http rest