gpt4 book ai didi

javascript - Ajax 部分加载静态 Rails

转载 作者:太空宇宙 更新时间:2023-11-04 16:28:55 26 4
gpt4 key购买 nike

在我的 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(未找到)

最佳答案

快速回答/相关SO答案:Rendering partial in js.erb file

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

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)
});

非常简单,但更重要的是试图概述一种不同的方法。这似乎也像 handlebars可以提供帮助。

关于javascript - Ajax 部分加载静态 Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39990049/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com