如何从 rails 4 中的 .js.erb 文件渲染部分? [英] How can I render a partial from .js.erb file in rails 4?

查看:47
本文介绍了如何从 rails 4 中的 .js.erb 文件渲染部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 rails 应用程序中,我在/assets/javascript 文件夹中有 dragdrop.js.erb.其中我有一个 ajax 块,它应该通过单击操作在 div 中呈现部分.我尝试了很多东西,但我无法让它工作.任何帮助将不胜感激.

In my rails application I have dragdrop.js.erb in /assets/javascript folder. In which I have an ajax block which should render a partial in a div with an on click action. I tried many things but I can't get it working. Any help would be appreciated.

代码如下:

 $.ajax({  
   type: "GET",    
   url: "<%=  Rails.application.routes.url_helpers.cookbooks_path %>",
   success: function(resp){
  $("#property").load("<%= escape_javascript (render :partial => 'recipes/package_form') %>") 
   }

推荐答案

Asset Pipeline

首先,您需要确保不要直接在您的 javascript 中使用任何 Rails 动态路径助手.

Firstly, you need to make sure that you don't use any Rails dynamic path helpers in your javascript directly.

问题在于,如果您预编译资产管道,您通常会发现这些动态路径助手无法正常工作.虽然它没有什么错误"——我倾向于将 Rails 后端代码与前端完全分开,以确保应用程序的多功能性:

The issue is that if you pre-compile your asset pipeline, you'll typically find these dynamic path helpers won't work correctly. Although there's nothing "wrong" with it - I tend to keep Rails back-end code completely separate from the front-end, as to ensure the versatility of the application:

#app/assets/javascripts/application.js
$(document).on("click", ".element", function(){
   $.ajax({  
     type: "GET",    
     url: "/cookbooks"
  });
});

这将向您的控制器后端发送一个裸"Ajax 请求(无参数/正文):

This will send a "naked" Ajax request (no params / body) to your controller backend:

#app/controllers/cookbooks_controller.rb
Class CookbooksController < ApplicationController
   def index
      @cookbooks = Cookbook.all
      respond_to do |format|
        format.html
        format.js #-> loads /views/cookbooks/index.js.erb
      end
   end
end

这里的技巧是,您现在可以使用渲染部分所需的参数填充 index.js.erb 文件:

The trick here is that you can now populate your index.js.erb file with the params necessary to render the partial:

#app/views/cookbooks/index.js.erb
$("#property").html("<%=j render :partial => 'recipes/package_form' %>") 

--

这应该对你有用

这篇关于如何从 rails 4 中的 .js.erb 文件渲染部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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