最佳实践使用AJAX没有Rails的内置助手? [英] Best practices for using AJAX without Rails' built-in helpers?

查看:114
本文介绍了最佳实践使用AJAX没有Rails的内置助手?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的博客上的应用程序,一些职位出现摘录 - 也就是说,用户看到的第一个(比方说)500个字符,并可以单击链接来查看整个帖子。下面是相关的部分:

In my blog application, some posts appear as excerpts -- i.e., the user sees the first (say) 500 characters, and can click a link to view the entire post. Here is the relevant partial:

<% href = url_for post_path(:id => post) %>

<h1 class="title"><%= post.title %></h1>
<h2 class="published_on"><%= post.author %> wrote this <%= time_ago_in_words(post.published_on)%> ago</h2>
<div class="body">
  <% if defined?(length) %>
    <%= truncate_html(post.body, :length => length, :omission => "&hellip;<h1><a class='more' href=\"#{href}\">Click here for more!</a></h1>") %>
  <% else %>
    <%= post.body %>
  <% end %>
</div>

而不是

然而,点击这里了解更多!以用户为一个单独的页面,我想它来填充后内嵌的其余部分。目前,我已经实现这个通过将上述片段在以下DIV:

However, instead of "Click here for more!" taking the user to a separate page, I'd like it to populate the rest of the post inline. Currently, I've been implementing this by putting the above snippet in the following div:

<div class="post" id="post_<%= post.id %>">
  <%= render :partial => 'post_content', :locals => { :post => post, :length => 500 } %>
</div>

然后我用这个div的ID在我的application.js做AJAX:

I then use the id of this div in my application.js to do the AJAX:

$(document).ready(function() {

  $("a.more").click(function() {
    var url = $(this).attr('href');
    var id = url.split("/")[2]
    $.get(url, null, function(data) {
      $("#post_" + id).html(data);     
    });
    return false;
  });

});

这是明显的恶心 - 我不希望我的JavaScript依赖于后期的ID在链接的href的位置,但我不知道任何其他方式的JavaScript知道哪个张贴的获取和因此在其中div中应插入的内容。

This is obviously disgusting -- I don't want my javascript to depend on the location of the post's id in the link's href, but I don't know any other way for the javascript to know which post it is getting and therefore into which div the content should be inserted.

什么是实现这一目标的最佳途径?我是不是应该回去使用Rails的AJAX佣工?

推荐答案

贺拉斯,你是正确的。你根本不需要Rails的助手。为了实现非侵入式JavaScript涅槃,你放心好了,以避免它们(对不起马克!)

Horace, you are correct. You don't need the Rails helpers at all. To achieve unobtrusive JavaScript Nirvana, you will do well to avoid them (sorry Marc!)

Unobstrusive JS意味着避免嵌入式JS在可能的情况。事实上,尽量让事情变得松散,但并非完全脱钩。在您给我们的例子中,很容易的,因为我们从HREF的URL的工作。您的JS并不需要知道如何申请任何东西。

Unobstrusive JS means avoiding embedded JS where possible. Indeed, try to keep things loosely coupled, but not entirely decoupled. In the example you gave us, it is easy, because we have a URL from the HREF to work with. Your JS does not need to "know" anything about how to request.

下面是如何通过发送从HREF的盲目的链接,并获得的Rails与Aja​​x响应(即没有布局)作出回应。

Here is how to send through the link from the HREF's blindly, and get Rails to respond with an ajax response (i.e. no layout).

解决方法:

<!------- Your HTML ------>
<h1 class="title">Schwein Flu Strikes Again</h1>
<h2 class="published_on">B.Obama wrote this 2 seconds ago</h2>
<div class="body">
    SUMMARY SUMMARY
    <h1><a class='more' href="/post/1234">Click here for more!</a></h1>
</div>

/********* Your JavaScript ***********/
$(document).ready(function() {

  $("a.more").click(function() {
    $containing_div = $(e).parents('div.body');
    var url = $(this).attr('href');
    $.ajax({
    	beforeSend	: function(request) { request.setRequestHeader("Accept", "text/javascript"); },
                        /* Included so Rails responds via "format.js" */
    	success		: function(response) { $(containing_div).empty.append(response); },
    	type		: 'get',
    	url		    : url
    });
    return false;
  });

});

########### Your Controller ###########
def show
  @article = Post.find(param[:id])
  respond_to do |format|
    format.html { render :action => "show" and return  }
    format.js { render :partial => "post_content", :layout => false and return }
  end
end

这也假设你有REST风格的路线或类似的处理/后/:ID

This also assumes you have RESTful routes or similar to handle /post/:id

和我们就大功告成了!我相信,有东西在,对我们所有人。 :D

And we're done! I believe there is something in that for all of us. :D

这篇关于最佳实践使用AJAX没有Rails的内置助手?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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