0

I want to open a json file on my JavaScript code, as this one:

[{
  "x1": "5",
  "y1": "5",
  "x2": "7",
  "y2": "6"
}, {
  "x1": "5",
  "y1": "4",
  "x2": "8",
  "y2": "8"
}]

Initially, I tried to open a local file, but it's not possible, right?

I tried this:

var xmlhttp = new XMLHttpRequest();
var dados = "file:///home/dan/Desktop/data.json";

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    myFunction(xmlhttp);
  }
};
xmlhttp.open("GET", dados, true);
xmlhttp.send();

function myFunction(response) {
  var arr = JSON.parse(response);
  var i;
  var out = "<table>"
  for (i = 0; i < 2; i++) {
    out += "<tr><td>" +
      arr[i].x1 +
      "</td><td>" +
      arr[i].x1 +
      "</td><td>" +
      arr[i].x1 +
      "</td></tr>";
  }
  out += "</table>";
}

(this create a table, just to test if it's working).

Or what should I do to open a Json file? Use XAMPP? How can I use XAMPP? Or there are another solution?

Thanks

t.niese
  • 39,256
  • 9
  • 74
  • 101
  • Are there errors in the developer console? (Press F12) Also, it should be `myFunction(xmlhttp.responseText)` – 4castle May 29 '16 at 15:02
  • The default behaviour of browsers is to block requests to local files (`file://`) using `XMLHttpRequest`. You could relax that rule using certain settings but your really shouldn't do that, because you might forget that you changed that settings, and if you then get on a malicious site it will be able to read your local data. – t.niese May 29 '16 at 15:05
  • Which browser are you using? – guest271314 May 29 '16 at 15:07
  • You are passing the request object to `myFunction`, try passing `.responseText` property of request object `myFunction(xmlhttp.responseText)` . See also http://stackoverflow.com/questions/32996001/jquery-load-only-working-in-firefox – guest271314 May 29 '16 at 15:15

0 Answers0