如何查询JSON值并将其包含在javascript中的rails helper中?

时间:2014-04-13 20:45:31

标签: javascript ruby-on-rails json ruby-on-rails-4 inline

如何将json值输入rails帮助器(用于删除位置)。

所以我的剧本的摘录是这样的,我真正合作的是最后一行。

var popupContent = '<div class="popup">' +'<img src="' + feature.properties.image.image.url + '">' +
              '<p style="font-size:94%">' + feature.properties.user_id + ' posted: ' +
               '<p>' + feature.properties.title + '</p>' +
               '<p><span class="timeago" title="'+feature.properties.created_at+'"></span>'+'</p><p><a href="/locations/'+feature.properties.name+'/edit">Edit</a> | ' +
               '<%= link_to "Destroy", @location, method: :delete, data: { confirm: "Are you sure?" } %>';

我尝试过的一种方法是将@location更改为"location/'+feature.properties.name+'",HTTP请求不会将JSON值添加到rails帮助程序。因此,rails不知道我要删除的位置。

根据请求,这是完整的javascript:

    function load(geojson) {
      // Fetch just the contents of a .geojson file from ... by passing
      // `......` to the Accept header
      // As with any other AJAX request, this technique is subject to the Same Origin Policy:
      // http://en.wikipedia.org/wiki/Same_origin_policy the server delivering the request should support CORS.
      $.ajax({
        headers: {
          'Accept': 'localhost'
        },
        dataType: 'json',
        url: '/locations.json',
        success: function(geojson) {

          // setting URL for json call below.
            // var url = '/locations.json';
          // initializing map, dark theme, and view.

            var map = L.mapbox.map('map', 'examples.map-y7l23tes')
                .addControl(L.mapbox.geocoderControl('examples.map-y7l23tes'))
                .setView([40.7178591652903, -73.985538482666], 12);
                L.control.locate({
                      position: 'topleft',  // set the location of the control
                      drawCircle: true,  // controls whether a circle is drawn that shows the uncertainty about the location
                      follow: false,  // follow the user's location
                      setView: true, // automatically sets the map view to the user's location, enabled if `follow` is true
                      keepCurrentZoomLevel: false, // keep the current map zoom level when displaying the user's location. (if `false`, use maxZoom)
                      stopFollowingOnDrag: false, // stop following when the map is dragged if `follow` is true (deprecated, see below)
                      circleStyle: {radius: 0, weight:3, color: '#ee0', fill: false, opacity:0.25},  // change the style of the circle around the user's location
                      markerStyle: {},
                      followCircleStyle: {},  // set difference for the style of the circle around the user's location while following
                      followMarkerStyle: {},
                      icon: 'icon-location',  // `icon-locate` or `icon-direction`
                      iconLoading: 'icon-spinner  animate-spin',  // class for loading icon
                      circlePadding: [0, 0], // padding around accuracy circle, value is passed to setBounds
                      metric: true,  // use metric or imperial units
                      onLocationError: function(err) {alert(err.message)},  // define an error callback function
                      onLocationOutsideMapBounds:  function(context) { // called when outside map boundaries
                              alert(context.options.strings.outsideMapBoundsMsg);
                      },
                      strings: {
                          title: "",  // title of the locate control
                          popup: "Hello! Seems like you're here.",  // text to appear if user clicks on circle
                          outsideMapBoundsMsg: "You seem located outside the boundaries of the map" // default message for onLocationOutsideMapBounds
                      },
                      locateOptions: {maxZoom: 17}  // define location options e.g enableHighAccuracy: true or maxZoom: 10
                  }).addTo(map);


          // center on tooltip click.
            map.featureLayer.on('click', function(e) {
                map.panTo(e.layer.getLatLng());
            });


          // adding a new marker
            var new_event_marker;
            map.on('click', function(e) {
             if(typeof(new_event_marker)==='undefined')
                {new_event_marker = new L.marker(e.latlng,{ draggable: false});
                new_event_marker.addTo(map)
                .bindPopup('<%= form_for @location, :html => {:multipart => true} do |f| %><% if @location.errors.any? %><div id="error_explanation"><h2><%= pluralize(@location.errors.count, "error") %> prohibited this location from being saved:</h2><ul><% @location.errors.full_messages.each do |msg| %><li><%= msg %></li><% end %></ul></div><% end %><h1>Post it!</h1><p>Click a spot on the map to tag your location.</p><div class="field hide"><%= f.label :latitude %><br><%= f.text_field :latitude, :id => "latitude" %></div><div class="field hide"><%= f.label :longitude %><br><%= f.text_field :longitude, :id => "longitude" %></div><div class="field"><%= f.text_field :title, autofocus: true, placeholder: "Whats going on?" %></div><div class="field"><br><%= f.file_field :image %></div><div class="actions"><%= f.submit "POST" %></div><% end %>').openPopup();   
                window[e.type].innerHTML = e.containerPoint.toString() + ', ' + e.latlng.lng.toString()+ '' + e.latlng.lat.toString();

              latitude.value = e.latlng.lat.toString();
              longitude.value = e.latlng.lng.toString();

              var click = document.getElementById('click'); 
             } else {
              new_event_marker.setLatLng(e.latlng).openPopup();
              window[e.type].innerHTML = e.containerPoint.toString() + ', ' + e.latlng.lng.toString()+ '' + e.latlng.lat.toString();

              latitude.value = e.latlng.lat.toString();
              longitude.value = e.latlng.lng.toString();

              var click = document.getElementById('click'); 
             }
             });


          // for clickable coords //

          $('#map').on('click', '', function() {

              var latitude = document.getElementById('latitude');
              var longitude = document.getElementById('longitude');

              map.on('click', function(e) {
              window[e.type].innerHTML = e.containerPoint.toString() + ', ' + e.latlng.lng.toString()+ '' + e.latlng.lat.toString();

              latitude.value = e.latlng.lat.toString();
              longitude.value = e.latlng.lng.toString();

              var click = document.getElementById('click'); });

});
            // On success add fetched data to the map.
            L.mapbox.featureLayer(geojson).addTo(map);

            // Add custom popups to each using our custom feature properties
            map.featureLayer.on('layeradd', function(e) {

                var marker = e.layer,
                    feature = marker.feature;
                // Create custom popup content
                var popupContent = '<div class="popup">' +'<img src="' + feature.properties.image.image.url + '">' +
              '<p style="font-size:94%">' + feature.properties.user_id + ' posted: ' +
               '<p>' + feature.properties.title + '</p>' +
               '<p><span class="timeago" title="'+feature.properties.created_at+'"></span>'+'</p><p><a href="/locations/'+feature.properties.name+'/edit">Edit</a> | ' +
               '<%= link_to "Destroy", @location, method: :delete, data: { confirm: "Are you sure?" } %>';

                // http://leafletjs.com/reference.html#popup
                return marker.bindPopup(popupContent,{
                    closeButton: false,
                    minWidth: 320
                }); 
            });

                // hover to see tooltip
                map.featureLayer.setGeoJSON(geojson);
                  // map.featureLayer.on('mouseover', function(e) {
                  //     e.layer.openPopup();
                  // });
                  // map.featureLayer.on('mouseout', function(e) {
                  //     e.layer.closePopup();
                  // });


                  // setting up timeline view.
                  var info = document.getElementById('info');

                  // Iterate through each feature layer item, build a
                  // marker menu item and enable a click event that pans to + opens
                  // a marker that's associated to the marker item.
                  map.featureLayer.eachLayer(function(marker) {
                    var link = info.appendChild(document.createElement('a'));
                    link.className = 'item';
                    link.href = '#';

                    // Populate content from each markers object.
                    link.innerHTML = '<img src="' + marker.feature.properties.image.image.url + '" style="width:50px; height:auto;">'+ marker.feature.properties.title +
                      '<br /><small>' + marker.feature.properties.user_id + '</small>';
                    link.onclick = function() {
                      if (/active/.test(this.className)) {
                        this.className = this.className.replace(/active/, '').replace(/\s\s*$/, '');
                      } else {
                        var siblings = info.getElementsByTagName('a');
                        for (var i = 0; i < siblings.length; i++) {
                          siblings[i].className = siblings[i].className
                            .replace(/active/, '').replace(/\s\s*$/, '');
                        };
                        this.className += ' active';

                        // When a menu item is clicked, animate the map to center
                        // its associated marker and open its popup.
                        map.panTo(marker.getLatLng());
                        marker.openPopup();
                      }
                      return false;
                    };
                  });


        }
      });
    }
    $(load);

1 个答案:

答案 0 :(得分:0)

这有帮助吗?

html.erb内部

<script type="text/javascript">
 var location=<%= @location %> 
</script>

内部.js

var popupContent = '<div class="popup">' +'<img src="' + feature.properties.image.image.url + '">' +
              '<p style="font-size:94%">' + feature.properties.user_id + ' posted: ' +
               '<p>' + feature.properties.title + '</p>' +
               '<p><span class="timeago" title="'+feature.properties.created_at+'"></span>'+'</p><p><a href="/locations/'+feature.properties.name+'/edit">Edit</a> | ' +
               '<%= link_to "Destroy", location, method: :delete, data: { confirm: "Are you sure?" } %>';