2013-11-01 126 views
0

我想加載外部json文件並將其與d3.js結合使用,但似乎無法加載(我無法在瀏覽器中看到us-states.json文件)該文件,我找不到任何相關的錯誤。這裏是我的代碼: -無法使用d3.js加載外部json文件

我收到此錯誤: - ActionController::RoutingError (No route matches [GET] "/us-states.json"):

$(document).ready(function() { 
         //Width and height 
     var w = 500; 
     var h = 300; 

     //Define map projection 
     var projection = d3.geo.albersUsa() 
          .translate([w/2, h/2]) 
          .scale([500]); 

     //Define path generator 
     var path = d3.geo.path() 
        .projection(projection); 

     //Create SVG element 
     var svg = d3.select("#testing") 
           .append("svg") 
           .attr("width", w) 
           .attr("height", h); 

     //Load in GeoJSON data 
     // json = JSON.parse("us-states.json"); 
     // var json = {"my": "json"}; 
     d3.json("us-states.json", function(error, json) { 
       if (error) return console.warn(error); 
       //Bind data and create one path per GeoJSON feature 
       svg.selectAll("path") 
        .data(json.features) 
        .enter() 
        .append("path") 
        .attr("d", path) 
        .style("fill", "steelblue"); 

     }); 
}); 

文件US-state.json是在我的javascript文件是同一個文件夾。

更新

錯誤在JavaScript控制檯是這樣的: -

Failed to load resource: the server responded with a status of 404 (Not Found) 

在文件US-states.json

附截圖顯示的文件是在項目文件夾: - enter image description here

+1

你是什麼意思「它似乎並沒有加載」? –

+0

@LarsKotthoff我的意思是我無法在瀏覽器中看到us-states.json文件 –

+0

這意味着它不在那裏。仔細檢查您是否已將其上傳到正確的地方。 –

回答

0

該代碼在哪個文件中? index.html(或某些等價物?)

您在使用json文件顯示的文件夾中沒有任何網絡文件。 json文件需要與名爲javascript的頁面位於相同的文件夾中,與d3.js不在同一文件夾中因此,假設您的web文件位於您的根目錄,您稱之爲d3-project,那麼正確的路徑是:app/assets/javascripts/us-states.json

此外,它是一個內部文件,因爲您已經在服務器上擁有它。外部意味着你正在打一個非你自己的網絡服務器並下載它。

+0

代碼在home.html中,我試圖給路徑,但它沒有工作 –

0

您也可以將us-states.json文件粘貼到您的公共文件夾中,並將其視爲本地文件夾(即保留您的代碼原樣)。

在一個Rails應用程序的一個D3地圖的例子來看看這個: https://github.com/lisafeather/map_in_app