简体   繁体   中英

Is making POST requests with additional parameters via link_to acceptable?

It's easy to make a link in Rails make a POST request. Something like link_to 'Click me', some_path, :method =>:post . This works great... unless you need to pass additional parameters in. Because there's no way to make an actual POST request from a link, Rails fakes it with a GET request, so that means if you try to pass additional parameters to some_path , it builds it into the query string. So when you mouseover you get a link that looks like this:

/some_path?foo=var&foo=bar[foo][bar]

Normally this wouldn't be too bad, except it gets really ugly if you've got a controller that is expecting some nested params.

So my question is, does this bother anyone else, or is just me?

The only workaround I can think of is to change the href to a # , add a hidden form nearby, and add a click handler to the link that serializes the form and submits it when the link is clicked. That makes the link degrade ungracefully and is an awful lot of work for what basically amounts to an aesthetic gripe. But I'm pretty obsessive about my URLs. Is there an easier way? Or am I just being crazy and should just deal with the params in the query string?

The web is an ugly place, and one of the things that's annoying is you can't make a link POST without creating a form or doing some wild JavaScript to handle it in the background.

It bothers people who are concerned with how tidy their URLs are, which is a concern far too few actually have in all honesty, but the only reliable solution is a form plus a tidy little jQuery extension to handle the trigger.

To avoid seeing an ugly URL in the browser, though, you can always make the request via AJAX, send back a URL, then redirect to that URL once the AJAX part is completed. This gives you the opportunity to present a "Submitting" or "Requesting" type spinner.

How about something like the following:

<html>
<head>
<script>
function myOnClick() {
  // ... do custom ajax w/whatever parameters.
  alert("myOnClick()");
}
</script>
</head>
<body>
<a href="http://www.example.com/" onClick="myOnClick();return false;">link text</a>
</body>
</html>

The browser will show the href value in the status bar, but the myOnClick() function is what is actually called when the link is clicked. The return false part is required to prevent the browser from processing the href attribute.

The myOnClick() function can the perform whatever operation, like an ajax request, with whatever parameters you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM