javascript 检查文件是否存在 [英] javascript check if file exists

查看:33
本文介绍了javascript 检查文件是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下使用 D3.js 加载 json 数据的代码:

i have the following code which uses D3.js to load json data:

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"?

what is the correct way to check if the file exists adm1_path = "../topo/"+d.id+"_adm1.json" before actually drawing the map?

推荐答案

你可以包含这样的函数:

You can include a function like this:

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

然后像这样修改你的代码:

And then modify your code like so:

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) {

这篇关于javascript 检查文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆