简体   繁体   English

在Rails 5.1.4中包含JS脚本

[英]include JS script in Rails 5.1.4

WHen I use the tags on the view page, the map shows and file runs fine. 当我在查看页面上使用标签时,地图显示出来,文件运行正常。 It does not show map or run script when I put the script in the app/assets/javascripts folder and call it. 当我将脚本放入app / assets / javascripts文件夹并调用它时,它不显示地图或运行脚本。 This is what I have. 这就是我所拥有的。 Any ideas? 有任何想法吗? Thank you. 谢谢。

config/intializers/assets.rb: config / intializers / assets.rb:

    Rails.application.config.assets.precompile += %w( mapshow.js )

app.assets/views/locations/map.html.erb app.assets / views / locations / map.html.erb

   <%= javascript_include_tag 'mapshow' %>

assets/javascripts/mapshow.js 资产/javascripts/mapshow.js

var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(37.725685, -122.156830),
mapTypeId: google.maps.MapTypeId.ROADMAP
});

var places = <%= @locations.to_json.html_safe %>
var infowindow = new google.maps.InfoWindow();
var marker, i;

for (i = 0; i < places.length; i++) {

marker = new google.maps.Marker({
  position: new google.maps.LatLng(places[i].lat, places[i].lng),
  map: map
});

google.maps.event.addListener(marker, 'click', (function(marker, i) {
  return function() {
    infowindow.setContent(places[i].location_name + "   <br />  " + places[i].location_description  + "    <br />     " + places[i].location_address);
    infowindow.open(map, marker);
  }
})(marker, i));
}
  1. You are using ERB syntax in your js file, which is not how 'precompiling' works. 您正在js文件中使用ERB语法,而这不是“预编译”的工作方式。
  2. Open your browser and find the line generated by javascript_include_tag . 打开浏览器,找到javascript_include_tag生成的行。 Copy the address and paste it in your address bar. 复制地址并将其粘贴到地址栏中。 Check if the file is downloaded. 检查文件是否已下载。
  3. If you want to upload js files modified by ERB, you should add them to your views with .js.erb extension and download them using XHR (you would need to define new controller and route for this as well) 如果要上传由ERB修改的js文件,则应使用.js.erb扩展.js.erb它们添加到视图中,并使用XHR下载它们(您还需要为此定义新的控制器和路由)

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

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