Xmlhttprequest problem

Asked

Viewed 52 times

-1

I am reading a JSON file that is located in a folder within the main project using Javascript. The code works in all browsers except Google Chrome. Error that appears in Chrome:

inserir a descrição da imagem aqui

Code:

function readJsonFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}

    function pintarMapa(estado, strokeColor, fillColor)
{
    readJsonFile("file:///Estados/"+estado+".json", function(data) {
        var dados = JSON.parse(data);
        var coord = new google.maps.Polygon({
            paths: dados.borders,
            strokeColor: strokeColor,// cor da borda
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: fillColor,// cor da área
            fillOpacity: 0.3
          });
        coord.setMap(map);
        console.log(dados);
    });
}

2 answers

1


You cannot execute an AJAX request for a local file.

If it is part of the project then you can access it by the relative path, for example, "~/Estados/"+estado+".json".

Something like that:

readJsonFile("~/Estados/" + estado + ".json", function (data) {
    // código
});
  • I don’t understand, so what changes in the code?

  • I edited the answer, I hope it helps.

  • The error continues...

  • Does the project have a server part? You will need to have a local server running (apache in the case of linux, or IIS in the case of c#, for example). Only with Javascript you won’t be able to read the file, it’s a security measure of current browsers, only older versions of IE allow.

  • So, even with all the . json files in my folder I won’t be able to read on google Chrome? The project isn’t on a server.

  • Exactly, the security of Chrome is tighter but I believe that in the future all browsers will have the same behavior. An alternative (untested) is to host for example in Dropbox and use the generated link to access json.

  • If my initial response helped to understand the problem and how it works when files are on the server, please mark as the correct answer

Show 2 more comments

0

I think your problem is on the line:

"readJsonFile("file://States/"+state+". json", Function(date) {"

You have 3 "/", put the correct way and test.

  • Not, file:// and only Estados/... do not work

Browser other questions tagged

You are not signed in. Login or sign up in order to post.