Rails 3 / Ajax - 将link_to转换为Jquery链接

时间:2011-07-26 20:10:20

标签: jquery ruby-on-rails ajax ruby-on-rails-3

我正在尝试将超链接更改为ajax链接。这样我可以在更新模型数据时链接到外部目标,而无需将用户发送到自定义控制器操作来处理发布/重定向。

我的应用程序是一个基本的图库,每个图像都链接到一个外部网站:

这是我的部分_pictures.html.erb:

<% @galleries.each do |g| %>
    <% for image in g.images %>
    <div id="picture">
      <%= render 'top_nav'%>

      <%= link_to g.source, :target => true do %>
        <%= image_tag image.file_url(:preview) %>
      <% end %>

      <%= will_paginate(@galleries, :next_label => "Forward", :previous_label => "Previous") %>
    </div>

    <br />

    <div class="image_description">
      <h2>
      <%= g.title %>,
      <span class="time">
        <%= distance_of_time_in_words(g.created_at, Time.now, include_seconds = false)%> ago
      </span>
      </h2>
    </div>      
    <% end %>
<% end %>

在我的index.html.erb上呈现的内容:

<h1>Share and click images to unlock more...</h1>

<div id="galleries">
<%= render 'pictures' %>
</div>

我相信我已经能够通过application.js中的以下内容将链接更改为ajax链接:

$(function() {
  $("#picture a").live("click", function() {

    return false;
  });
});

由于link_to不起作用(我预期)。现在,我正在尝试在index.js.erb中编写处理程序(不确定这是否是正确的单词),我知道这是错误的,但我拼凑的是:

$("#picture").html.("<%= escape_javascript(render)("pictures")) %>")

如何通过javascript将此链接恢复正常?如果我想对模型方法进行ajax调用,那么我将在application.js或index.js.erb中开始编写该代码?

强制性防御机制:我吮吸javascript。

3 个答案:

答案 0 :(得分:0)

$(function() {
    $("#picture a").live("click", function(event) {
        event.preventDefault(); // prevent the click from linking anywhere

        $.ajax({
            url:'/my_ajax_file.erb',
            dataType:'html',
            data: $(this).attr('id'), // send whatever here...
            type: 'post',
            success:function(data){
                $('#picture').html(data);
            }
        });

    });
});

答案 1 :(得分:0)

尝试$("#picture").html("<%= escape_javascript(render("pictures")) %>");

但是如果你使用prototype和jquery为jQuery.noConflict()

更改$
  $(function() {
      $("#picture a").live("click", function() {
          $.getScript(this.href);
          return false;
      });
  });

答案 2 :(得分:0)

不要忘记在你的控制器中有这样的东西:

respond_to do |format|
   format.html do
      redirect_to #whatever you normally redirect to for html
   end
   format.js do
      render :json => some_json_thing #this will get passed back as the data element in the ajax callback above
   end
end