在rails中使用jquery参数进行link_to [英] link_to with jquery params in rails

查看:97
本文介绍了在rails中使用jquery参数进行link_to的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Rails应用中进行就地搜索.
我将button_to_remote与原型一起使用,但现在使用的是JQuery,因此我更改为link_to.
这是我的代码:

I want to make an in-place search in my rails app.
I used button_to_remote with prototype, but now I'm using JQuery, so I changed to link_to.
This is my code:

<%= link_to "Search", {:action => "geocode", :with => "'address='+$('#{address_helper_id}').value"}, :method => :post, :remote => true %>

我想将地址文本字段传递给我的控制器,但是输出不是我期望的.

I want to pass the address textfield to my controller, but the output is not what I expected.

/mycontroller/geocode?with=%27address%3D%27%2B%24%28%27record_location___address%27%29.value

我该如何提交我的价值?

How do I submit my value?

推荐答案

您可能想尝试一点也不引人注意的方法.我建议将您的link_to通话替换为以下内容:

You might want to try approaching things a little more unobtrusively. I would recommend replacing your link_to call with something like:

<%= link_to "Search", "#", :id => "search_geocode", :"data-href" => my_controller_geocode_path %>

这实际上与您已经拥有的相同,除了它在data-href属性中包括唯一的ID以及控制器/地理编码路径.这将帮助您将ruby和javascript分开一些.

This is virtually identical to what you already have, except that it includes a unique id, and also the controller/geocode path in an data-href attribute. This will help allow you to keep your ruby and javascript a bit more separated.

然后在您的application.js(或类似位置)中

Then in your application.js (or somewhere similar):

$('#search_geocode').live('click', function(event){
    event.preventDefault();
    $.post($(this).attr('data-href') + "?address=" + $('#address').val(), function(data){} );
});

这实际上是在将click事件侦听器绑定到您的搜索按钮,该事件侦听器会将地址发布到搜索链接的data-href属性中提供的网址或路径.

What this is effectively doing is binding a click event listener to your search button, which posts the address to the url or path provided in the data-href attribute of your search link.

我还注意到,在您的代码中,您将源地址的id设置为ruby.如果需要根据某种页面模板条件更改此id属性,则可以通过在链接中添加另一个data-参数来扩展我的示例.例如:

I also notice that in your code, you're setting the id of the source address in ruby. If this id attribute needs to change based on some sort of page template conditions, you could expand on my example by adding another data- parameter to your link. For example:

<%= link_to "Search", "#", :id => "search_geocode", :"data-href" => my_controller_geocode_path, :"data-address-id" => address_helper_id %>

再次,在application.js中,将上面的内容替换为以下内容:

And again, in application.js replacing above with something along the lines of:

$('#search_geocode').live('click', function(event){
    event.preventDefault();
    $.post($(this).attr('data-href') + "?address=" + $($(this).attr('data-address-id')).val(), function(data){} );
});

这篇关于在rails中使用jquery参数进行link_to的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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