简体   繁体   English

调用.js.erb文件而不是.html.erb文件

[英]call .js.erb file instead of .html.erb

I have Rails application with a google map. 我有带有Google地图的Rails应用程序。 I want to populate it with markers using a .js.erb file so that I have access to ruby variables in javascript. 我想使用.js.erb文件用标记填充它,以便可以访问javascript中的ruby变量。 I don't want to use gon gem. 我不想用gon gem。

Is there a way to have the action call .js.erb file instead of the .html.erb file? 有没有办法让操作调用.js.erb文件而不是.html.erb文件?

One way around this is to load the .html.erb and then have to do an automatic ajax call to load the .js.erb, but I'm looking for a better solution. 解决此问题的一种方法是加载.html.erb,然后必须执行自动ajax调用以加载.js.erb,但我正在寻找更好的解决方案。

Thanks. 谢谢。

The controller really isn't the right way to that, since its job is to respond to requests. 控制器确实不是正确的方法,因为它的工作是响应请求。 If a request comes in and expects to get HTML back, Rails will give HTML back. 如果有请求进入并希望重新获得HTML,Rails将会重新提供HTML。 If it's a JS request, it sends JS back. 如果是JS请求,则会将JS发送回去。

The right way to do this is to load the page with HTML and then do an AJAX call from the page. 正确的方法是使用HTML加载页面,然后从页面进行AJAX调用。 You can even send it to the same action and Rails will respond with the appropriate js.erb template. 您甚至可以将其发送到相同的操作,Rails将使用适当的js.erb模板进行响应。 If you want to give it special instructions, maybe if you want your JSON rendered in a specific way, you can do that with respond_to or the JBuilder gem. 如果要为其提供特殊说明,或者如果您想以特定方式呈现JSON,则可以使用respond_to或JBuilder gem来实现。

Edit: The above is written under the assumption that you are loading the page through a normal HTML request and you want it to do both HTML and JS. 编辑:以上内容是在您通过普通HTML请求加载页面并且希望它同时执行HTML和JS的前提下编写的。 If you are already on a page and you want to do an AJAX call through a link, button, or form without rendering HTML at all, you can do that by adding remote: true to any form_for , form_tag , button_to , or link_to tags. 如果您已经在页面上并且想要通过链接,按钮或表单进行AJAX调用而根本不呈现HTML,则可以通过在所有form_forform_tagbutton_tolink_to标记中添加remote: true来实现。

If you want to avoid a second call and have no expectation that your controller will need to respond with JSON, you can put the data you're looking for into HTML5 data attributes right in your view. 如果您希望避免再次调用,并且不希望控制器需要使用JSON进行响应,则可以在视图中将要查找的数据放入HTML5数据属性中。 Those exist specifically for the purpose of providing information to JS. 这些是专门为向JS提供信息而存在的。 You can just do one with its value set to an array containing your markers, then have your script run through each element of that array. 您只需将其值设置为包含标记的数组来执行一项操作,然后让脚本在该数组的每个元素中运行。

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

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