Modify code to avoid an XMLHttpRequest with $ .getJSON

0

I'm developing an application here, and I use a JSON object for popular, but when I use $.getJSON() Chrome gives the following error:

XMLHttpRequest can not load file: /// C: /Users/JeanCarlos/Documents/GitHub/NetworkDiagram/Application/Object.json. Cross source requests are only supported for protocol schemes: http, date, chrome, chrome-extension, https, chrome-extension-resource.

JavaScript

$(function() {
// This function get error XMLHtmlRequest, because this not supported protocol LOCAL.
$.getJSON('Object.json', function(data) {       
    console.log('success');
    var table = '';
    $.each(data.activies, function(key, val) {
        table += '<table>';
        table += '<tbody>';
        table += '<tr><td>' + val.EarlyStart + '</td><td>' + val.Duration + '</td><td>' + val.EarlyFinish + '</td></tr>';
        table += '<tr><td colspan="3">' + val.ActivityName + '</td></tr>';
        table += '<tr><td>' + val.LateStart + '</td><td>' + val.TotalFloat + '</td><td>' + val.LateFinish + '</td></tr>';
        table += '</tbody>';
        table += '</table>';
    });     
    $("#content").append(table);
}).error(function() {
    console.log('error');
});
});

Object.JSON

{"activies" = [{
"EarlyStart": "1",
"Duration": "10",
"EarlyFinish": "2",     
"ActivityName": "Activity 1",
"LateStart": "4",
"TotalFloat": "4",
"LateFinish": "5"                      
}]}

I understand the problem, that this error is a "half security" that chrome uses, but I need to modify this code to not give this problem anymore.

    
asked by anonymous 24.02.2016 / 17:31

1 answer

1

As Sergio Garcia said in the comment, this is not possible in Chrome, however you can easily create an http server by Node.js v5 +

Server: server.js

// Inicie o servidor na porta 8000 e mantenha o socket
// aberto até que o processo seja finalizado.
http.createServer(function(req, res) {
  // O conteúdo da resposta deve ser interpretado como texto
  // HTML com codificação UTF-8
  res.setHeader('Content-Type', 'text/html; charset=utf-8');

  try {
    // Leia o arquivo index.html e retorne o conteúdo HTML
    // para o cliente.
    res.writeHeader(200);
    res.write(fs.readFileSync('./index.html').toString());

  } catch(e) {
    // Houve um erro ao tentar ler o arquivo.
    res.writeHeader(500);
    res.write(JSON.stringify(e,0,2));

  }

  // Enviar o buffer ao cliente.
  res.end();
}).listen(8000).timeout = 0;

Client: index.html

// Arquivo index.html
<script>
  // Código da sua requisição
</script>

The files server.js and index.html must be in the same folder.

    
24.02.2016 / 19:36