2013-02-24 50 views
0

我有下面的代碼,它使用D3.js加載JSON數據:如果JavaScript的檢查文件是否存在

this.clickCountry = function(d) { 
    "use strict" 
    var time_for_remove = 500, 
     time_for_zoom = 900 
    d3.selectAll("svg g").transition().delay(time_for_remove + time_for_zoom - 200).remove() 
    self.svg.append("g") 
     .attr("id", "country") 
    self.regionsGroup = self.svg.select("#country") 
    var adm1_key = d.id+"_adm1" 
    try { 
     var adm1_path = "../topo/"+d.id+"_adm1.json" 
    } catch (e) { 
     console.log(e) // "MyError" 
    } 
    var adm1_path = "../topo/"+d.id+"_adm1.json" 
    d3.json(adm1_path, function(error, topology) { 
     var regions = topology.objects 
     for(var adm1_key in regions) { 
      var o = regions[adm1_key] 
     } 
     self.regionsGroup.selectAll("path") 
     .data(topojson.object(topology, o).geometries) 
     .enter().append("path") 
     .attr("d", self.projection) 
     .attr("id", function(d) { 
      return d.properties.name 
     }) 
     .classed("country", true) 
     .attr("class", "country") 
     .on("mouseover", function(d) { 
      d3.select(this) 
      .style("fill", "#6C0") 
      .append("svg:title") 
      .text(d.properties.name) 
     }) 
     .on("mouseout", function(d) { 
      d3.select(this) 
      .style("fill", "#000000") 
     }) 
     .on("click", function(d) { 
      console.log('clicked on country') 
      var p = d3.mouse(this)                  
      console.log(p+" "+self.map.invert(p))               
      self.map.center(self.map.invert(p)) 
     }) 
    }) 
} 

什麼是檢查文件是否存在adm1_path = "../topo/"+d.id+"_adm1.json"其實之前繪製地圖的正確方法?

+0

XHR和'onerror'可能? – 2013-02-24 17:07:51

+0

是的,檢查404錯誤代碼... – 2013-02-24 17:12:02

回答

3

可以包括這樣的功能:

function fileExists(url) 
{ 
    var http = new XMLHttpRequest(); 
    http.open('HEAD', url, false); 
    http.send(); 
    return http.status!=404; 
} 

然後修改,像這樣的代碼:

var adm1_path = "../topo/"+d.id+"_adm1.json" 
if (!fileExists(adm1_path)) { 
    alert('We couldn't find that country!') //or some other suitable error/display mechanism 
    return; 
} 

d3.json(adm1_path, function(error, topology) { 
+0

不錯的,謝謝 – khinester 2013-02-24 20:20:13