动态插入PARAMS Rails中的link_to到 [英] Dynamically insert params to link_to in Rails

查看:183
本文介绍了动态插入PARAMS Rails中的link_to到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的主页,我有一个输入框,用户可以输入一个搜索查询。然后,我有一个的link_to这将使一个GET请求到不同的网页(搜索页面)与搜索查询。在设计上,我不能使用的Rails的form_for。

In my homepage, I have an input box that user can type in a search query. Then I have a link_to which will make a get request to a different page (search page) with the search query. By design, I can't use Rails form_for.

在我的输入框中检测到变化后,我怎么可以插入我的查询动态地的link_to?

How can I insert my query dynamically to "link_to" after detecting a change in my input box?

下面是一个模拟的:

%input{:type => "text", :id => "my_input"}
= link_to "Search", posts_path(query: "my_query_here") 
:javascript
  $(function(){
      $("#my_input").change(function() {
          ... do something here ...
          });
  });

感谢你。

推荐答案

您不能。您的JavaScript无法侵入你的服务器端code。但是,它可以破解的结果的你的服务器端code,这是HTML。

You can't. Your javascript can't hack into your server-side code. However, it can hack the result of your server-side code, which is HTML.

要确保查询自己的帖子链接正确匹配,你应该添加一个特定的ID,以你的<%=的link_to%>

To make sure the query for your posts link matches properly, you should add a specific ID to your <%= link_to %>:

<%= link_to "Search", posts_path, :id => "search_link" %>

那么你的JavaScript应该是这样的:

Then your javascript should be like:

$("#my_input").change(function() {
   $("#search_link").attr("href","/posts?q=" + encodeURIComponent( $(this).val() ) );
});

由于用户@ beck03076的提示,你可以简单地执行对点击的位置改变,而不是每次更新的链接,输入的变化:

Thanks to user @beck03076 for suggesting that you could simply execute a location change on click rather than updating the link every time the input changes:

$("#link").click(function() {
    $(this).attr("href", "/posts?q=" + encodeURIComponent($("#my_input").val()));
});

根据究竟是什么,你想做的事,这可能确实不是你的预期相符。例如,如果你有一些其他的code,它可以检查链接URL更新别的网页上,第二种方法是行不通的。如果,另一方面,你想要的是执行上点击搜索,这将是更有效的。

Depending on what exactly you want to do, this may not exactly match your expectation. For example, if you have some other code that inspects the link URL to update something else on the page, this second method won't work. If, on the other hand, all you want is to execute a search on click, this will be much more efficient.

这篇关于动态插入PARAMS Rails中的link_to到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆