繁体   English   中英

Ajax 加载静态 Rails 部分

[英]Ajax Load Static Rails Partial

在我的 rails 应用程序中,我有一个 html 模板位于public/templates/_hero-1.html.erb

在我application.js.erb文件,我想该模板加载到div我动态创建的,之前我渲染整个div

// Append component to text editor when clicked
$('.js-TemplateThumbnail').click(function() {
    // Define new template container
    var newTemplateContainer = $('<div class="position-relative hideChild js-TemplateContainer">');

    // Insert selected template into new template container
    newTemplateContainer.load("<%= 'public/templates/hero-1' %>");

    // Build new template
    $('.js-Canvas .js-TemplateContainer').last().after(newTemplateContainer);
});

但我收到控制台错误GET http://localhost:3000/public/templates/hero-1 404 (Not Found)

快速答案/相关 SO 答案: 在 js.erb 文件中渲染部分

更长的答案:有几种方法可以做到这一点。 你可以试试:

newTemplateContainer.load("<%= 'render partial: public/templates/hero-1' %>");

不是积极的,会起作用。 这对我来说感觉很糟糕,并且还会给您留下高度耦合的代码。 如果该模板的名称发生更改,则必须在 n 个位置更新它。

我会解耦 JS 并在config/routes.rb创建一个内部端点; 例如:

get templates/:id

然后,

class TemplatesController < ApplicationController
  def show
    @template = Template.find(params[:id])
  end   
end

然后在单击处理程序内的 JS 中,您可以:

$.get('/templates/hero-1', function(data) {
   // do stuff with returned data
   $('.js-Canvas').html(data)
});

非常简单,但更多的是试图概述一种不同的方法。 这似乎也是车把可以提供帮助的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM