【问题标题】:catching javascript "unexpected end of input"捕获javascript“输入意外结束”
【发布时间】:2012-01-23 04:46:38
【问题描述】:

这是 Rails 应用程序中的一个视图 - 不幸的是,我遇到了一个我无法修复的错误(“未捕获的语法错误:输入意外结束”)。虽然我确信答案很简单,但添加一个额外的}); 并不能解决问题。

有人对我可能忘记在哪里关闭某些东西有任何想法吗?

谢谢!

在 HAML 中:

- content_for :before_head do
  = javascript_include_tag "http://maps.google.com/maps/api/js?sensor=false"


- content_for :page_javascript do
  = javascript_include_tag "http://www.mapnificent.net/media/api/1/mapnificent.js"
  :javascript
    var MAP, HEATMAP, DATAPOINTS;
    var mapnificent, urbanDistance, positions = {};
    $(document).ready(function() {
      DATAPOINTS = {};
      var myLatlng = new google.maps.LatLng(40.75297891717686, -73.93936157226562);

      var myOptions = {
            zoom: 12,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true,
            scrollwheel: true,
            draggable: true,
            navigationControl: true,
            mapTypeControl: false,
            scaleControl: true,
            disableDoubleClickZoom: false,
            streetViewControl: false,
            mapTypeControl: false,
            overviewMapControlOptions: false,
            styles: [
                  {
                    featureType: "administrative",
                    elementType: "geometry",
                    stylers: [
                      { visibility: "off" }
                    ]
                  },{
                    featureType: "administrative.locality",
                    stylers: [
                      { visibility: "on" }
                    ]
                  },{
                    featureType: "transit.line",
                    stylers: [
                      { visibility: "off" }
                    ]
                  },{
                    elementType: "geometry",
                    stylers: [
                      { saturation: -100 },
                      { lightness: -100 },
                      {gamma:0.24}
                    ]   
                  },{
                    featureType: "road.arterial",
                    elementType:"labels",
                    stylers: [
                      { visibility: "simplified" },
            //        { saturation: -100 },
            //        {lightness:70},
            //        {hue: "#ffc243"}
                    ]
                  },{
                    featureType: "road.highway",
                    elementType: "labels",
                    stylers: [
                      { visibility: "simplified" },
            //        { saturation: -100 },
            //        {lightness:70},
            //        {gamma: 0},
                    ]   
                  },{
                    featureType: "landscape",
                    elementType: "geometry",
                    stylers: [
                      { lightness: 92 },
                      { saturation: 20 },
                      { hue: "#e2ded3" },
                    ]
                  },{
                    featureType: "road",
                    elementType: "geometry",
                    stylers: [
                      { visibility: "simplified"},
                      { saturation: 10 },
                      { lightness: 100 },
                      { hue: "#ffc243" }
                    ]
                  },{
                    featureType: "water",
                    stylers: [
                      { visibility: "simplified" },
                      { lightness: 70 },
                      { saturation: 15 },
                      { hue: "#00ffdd" }
                    ]
                  },{
                    featureType: "poi",
                    elementType: "geometry",
                    stylers: [
                      { visibility: "on" },
                      { saturation: 15 },
                      { lightness: 89 },
                      { hue: "#e2ded3" }
                    ]
                  },{
                    featureType: "transit.station",
                    elementType: "geometry",
                    stylers: [
                      { visibility: "simplified" },
                      { lightness: 85 },
                      { hue: "#e2ded3" },
                      { saturation: 15 }
                    ]
                  },
                  {
                    featureType: "poi.park",
                    elementType: "geometry",
                    stylers: [
                      { hue: "#61bb00" },
                      { lightness: -15},
                      { saturation: 20},
                      { visibility: "simplified" }
                    ]
                  },{
                    featureType: "transit.station",
                    elementType: "labels",
                    stylers: [
                      { hue: "#06bca9" },
                      { saturation: -30},
                      { lightness: -10},
                      { visibility: "on" }
                    ]
                  }
                ]

            };

      MAP = new google.maps.Map(document.getElementById("map"), myOptions);








      /* 
       This is the UrbanDistance's (i.e. the public transport layer) UI function.
       This function gets called during the setup process and you can easily setup your UI in there 
       Parameters:
          mapnificent: the mapnificent instance, responsible for how to draw on the map
          that: the urbanDistance layer object, responsible for handling the public transport travel time calculation and drawing
          $: jQuery for your convenience, scoped to this function, shortcut to window
          undefined: the real undefined value, only 4 arguments are passed

      */

      var UrbanDistanceUI = function(mapnificent, that, $, window, undefined){
          /* that.bind binds a function to an event of the layer 
              setup is called when the setup of the layer is complete
              and before the loading of necessary data. 
          */
          that.bind("setup", function(){
              /* There are many options for the public transport layer 
              They can be read with .getOption and set with .setOption */
              var color = that.getOption("color");
              that.setOption("color", true);
              /* you must display this copyright notice somewhere on your page */
              $("#copyright").html(that.getOption("copyright"));
              console.log("setup done");
          });


          /* 
          loadProgress binds to the data loading progress,
          you will receive one parameter: a percentage */
          that.bind("loadProgress", function(progress){

              $('#loading').text(progress);
              if(progress >= 100){
                  $('#loading').text("Almost done...");
              }
          });

          /*
          fires when the data has finished loading */
          that.bind("dataLoaded", function(){
              $('#loading').text("Done!");
              var geopos = {lat:40.75297891717686,lng:-73.93936157226562}, time = 30 * 60;
              /* adds a position to the map at the specificed location.
              Time can be left out for the default time (15 minutes) */
              var pos = that.addPosition(geopos, time); // time in seconds!
              /* The call returns a position object that you can store.
              You can store it by it's index pos.index */
              positions[pos.index] = {position: pos, latlng: geopos};
              /* You only created a position, you need to start the
               calculation process explicitly */
              pos.startCalculation();
          });

          /* fires when a calculation has started, receives position as parameter */
          that.bind("calculationStarted", function(position){
              $('#loading').text("Starting calculation: 0.0%");
          });

          /* fires when there is a calculation progress, receives position as parameter */
          that.bind("calculationUpdated", function(position){
              /* estimating the progress is not an exact since 
              the option value "estimatedMaxCalculateCalls" is 
              an estimated upper bound of position.calculationProgress
              */
              var percent = position.calculationProgress /
                  that.getOption("estimatedMaxCalculateCalls") * 100;
              $('#loading').text("Calculating: "+percent+"%");
          });

          /*fires when the calculation is done */
          that.bind("calculationDone", function(position){
              $('#loading').text("Calculation Done!");
              console.log("done");
              /* you need to trigger a redraw of the canvas yourself at appropriate moments */
              mapnificent.trigger("redraw");
              /* see getBlobs function further down */
              getBlobs();
          });

          var movePosition = function(index, pos){
              /* you can move your position with the .move method of a position
              it takes an geo object {lat: X, lng:Y} as first parameter.
              last parameter indicates if positionMoved should be triggered */
              var result = positions[index].position.move(pos, true);
              /* result indicates if the position is in range of the current city data
                 if it is not, positionMoved has not been triggered, regardless of second parameter
                 it it is true, postionMoved has been triggered (it already executed)
                 the latlng field of the position is set regardless of anything
                 */
              if (!result){
                  console.log("moved outside of range!");
              }
          };
          /* triggered when a position moved inside the range */
          that.bind("positionMoved", function(pos){
              positions[pos.index].latlng = pos.latlng;
              console.log("position move to ", pos.latlng);
          });

          var removePosition = function(index){
              /* you can call removePosition on the UB layer with an index 
              to remove this position. This will also stop all ongoing calculations */
              that.removePosition(index);
          };

          /* fires after successful removal */
          that.bind("positionRemoved", function(index){
              console.log("position removed");
              delete startPositions[index];
              mapnificent.trigger("redraw");
          });

          var getBlobs = function(){
              /* A blob is a currently visible*, highlighted area that is 
              separate from other highlighted areas. The blob contains the 
              maxbounds in canvas coordinates, and some other information */

              var blobs = that.search.detectBlobs();
              console.log(blobs);
          };

      /* tried adding in a '}' here */    


















      google.maps.event.addListenerOnce(MAP, "idle", function() {
        HEATMAP = new HeatmapOverlay(MAP, {
            "radius": 30,
            "visible": true,
            "opacity": 60
        });

        getDataPoints("theater", "http://doug.cartodb.com/api/v2/sql/?q=SELECT ST_x(geom) AS lng, ST_y(geom) AS lat, count(*) FROM (SELECT ST_SnapToGrid(the_geom,0.005) AS geom FROM v_theaters) AS foo GROUP BY lng, lat");
        getDataPoints("noise", "http://doug.cartodb.com/api/v2/sql/?q=SELECT ST_x(geom) AS lng, ST_y(geom) AS lat, count(*) FROM (SELECT ST_SnapToGrid(the_geom,0.005) AS geom FROM noise) AS foo GROUP BY lng, lat");
        getDataPoints("4sqDrug", "http://doug.cartodb.com/api/v2/sql/?q=SELECT ST_x(geom) AS lng, ST_y(geom) AS lat, count(*) FROM (SELECT ST_SnapToGrid(the_geom,0.005) AS geom FROM _4sq_15_32_47_drugstores_20or_20pharmacies) AS foo GROUP BY lng, lat");        
       });





       if(typeof Mapnificent !== "undefined" && Mapnificent.isBrowserSupported()){
           /* load Mapnificent options for these coordinates */
           Mapnificent.forCoordinates({lat:40.75297891717686,lng:-73.93936157226562}, function(options){
               if(options == null){
                   /* if null, there is no Mapnificent data for this point */
                   return;
               }
               /* if there are options, you can instantiate a new Mapnificent instance */
               mapnificent = Mapnificent(options);
               /* add the "urbanDistance" layer with the UI function */
               mapnificent.addLayer("urbanDistance", UrbanDistanceUI);
               /* you can bind to the initDone event of mapnificent */
               mapnificent.bind("initDone", function(){
                   // mapnificent.hide();
               });
               /* finally add mapnificent to your map by passing the Google Maps instance */
               mapnificent.addToMap(map);
           });
       }





      /* tried removing a "});" from two lines below this comment */

    });

    function showHeatmap() {
      var max = 0;
      var all_points = [];
      for(var key in DATAPOINTS ) {
        DATAPOINTS[key].rows.forEach(function(row) {
          if (row.count > max) {
            max = row.count
          }
        });
        all_points = all_points.concat(DATAPOINTS[key].rows);
      }

      var testData = {
        max: max,
        data: all_points
      }

      HEATMAP.setDataSet(testData);
    }

    function getDataPoints(name, url) {
      $.get(url, function(data) {
        DATAPOINTS[name] = data;
        showHeatmap();
      });
    }

%b
  #loading
  #copyright

错误出现在下一个块之前 - 未捕获的语法错误:输入意外结束

.map_holder{:style => "float: left; width: 600px; height: 600px;"}
  #map{:style => "width: 100%; height: 100%; border: 1px solid #333;"}  
.side_bar{:style => "float: right;"}
  %p SideBar
  = label_tag "Noise Data"
  = check_box_tag "Test"
.cl{:style => "clear: both;"}

【问题讨论】:

  • 这是服务器端错误(Ruby/Haml)还是客户端错误(浏览器中的 JS)?如果是后者,那么发布您的 Haml 内容是没有用的:查看发送到浏览器的源代码并向我们展示那个代码。

标签: javascript ruby-on-rails ruby-on-rails-3 haml


【解决方案1】:

从 console.log() 的使用来看,我认为您现在没有在 IE 中进行测试。但如果错误出现在 IE 中,我会从以下行中删除尾随逗号:

{ visibility: "simplified" },

在这种情况下,我所知道的最好的调试技术是进行“二进制搜索”。去掉一半的代码(当然,不要直接砍到会留下不匹配的括号或大括号的地方),尝试在浏览器中运行,看看是否还有语法错误。重复,直到将其缩小到一小段代码。

【讨论】:

  • 嗨@Alex,我一直在 Firefox、Chrome 和 Safari 中进行测试。 Firebug 提供了比 Chrome DevTools 更多的帮助 - 我尝试在我的评论之后更改行 (` /* 尝试删除 "});"从这条评论下方的两行 */) and changed it from });` 到 }});,虽然页面现在避免了错误,但地图上的图层不会加载。
猜你喜欢
  • 2017-04-20
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2019-12-27
  • 1970-01-01
  • 2020-01-08
  • 2017-01-05
相关资源
最近更新 更多