[英]js.erb not rendering in rails 6
I'm having trouble rendering a.js.erb from an action.我在从动作中渲染 a.js.erb 时遇到问题。 The action triggers, and rails tells me that it's rendering the js.erb, but the js never gets rendered and is evident from the console logs in the js not rendering to the browser's console.
动作触发,rails 告诉我它正在渲染 js.erb,但 js 永远不会被渲染,并且从控制台日志中可以明显看出 js 没有渲染到浏览器的控制台。 I've tried a bunch of solutions online but can't seem to find out why rails would be telling me this js template is rendering, but not have it actually render in the browser.
我在网上尝试了一堆解决方案,但似乎无法找出为什么 rails 会告诉我这个 js 模板正在呈现,但实际上并没有在浏览器中呈现。 What could I be missing?
我会错过什么?
Controller action Controller 动作
def dynamic_search
puts "WE ARE IN DYNAMIC_SEARCH"
puts params[:q]
client = HTTPClient.new
string = 'call to google places api'
@result = client.get_content(string)
@hash = JSON.parse @result
render "home/dynamic_search.js.erb", format: :js
end
Rails terminal output导轨端子 output
Rendering home/dynamic_search.js.erb
Rendered home/dynamic_search.js.erb (Duration: 0.0ms | Allocations: 4)
Completed 200 OK in 479ms (Views: 0.7ms | ActiveRecord: 0.0ms | Allocations: 4613)
UPDATE:更新:
Code that calls the action is below (not 100% correct but just testing the call at the moment using JQuery easy-autocomplete)调用该操作的代码如下(不是 100% 正确,但目前只是使用 JQuery easy-autocomplete 测试调用)
document.addEventListener("turbolinks:load", function() {
$input = $('*[data-behavior="autocomplete"]')
var options = {
url: function(phrase){
console.log(phrase)
return '/search/' + phrase
}
}
$input.easyAutocomplete(options);
});
easy-autocomplete
is expecting dynamic_search
to return parsable data either (JSON or XML). easy-autocomplete
期望dynamic_search
返回可解析的数据(JSON 或 XML)。
It is not actually running the js in "dynamic_search.js.erb" in the current context.它实际上并没有在当前上下文中运行“dynamic_search.js.erb”中的 js。 This means that either the content of "dynamic_search.js.erb" needs to represent such an object after rendering or preferably the
dynamic_search
action should just render it directly.这意味着“dynamic_search.js.erb”的内容需要在渲染后表示这样的 object,或者最好是
dynamic_search
操作直接渲染它。
For Example (I will assume you want to use easy-autocomplete
with @result
)例如(我假设您想使用带有
@result
easy-autocomplete
)
def dynamic_search
puts "WE ARE IN DYNAMIC_SEARCH"
puts params[:q]
client = HTTPClient.new
string = 'call to google places api'
@result = client.get_content(string)
render json: @result
end
I am not sure what the @result
json actually looks like so you may need additional manipulation above or below.我不确定
@result
json 实际上是什么样子,因此您可能需要在上方或下方进行额外的操作。
Then the js could be:那么js可能是:
document.addEventListener("turbolinks:load", function() {
$input = $('*[data-behavior="autocomplete"]')
var options = {
url: function(phrase){
console.log(phrase)
return `/search/${phrase}`
}
}
$input.easyAutocomplete(options);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.