Modify code to avoid a Xmlhttprequest with $.getJSON

Asked

Viewed 90 times

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 cannot load file://C:/Users/Jeancarlos/Documents/Github/Networkdiagram/Application/Object.json. Cross origin requests are only supported for Protocol schemes: http, data, 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');
});
});

JSON object.

{"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 more this problem.

  • 4

    You cannot upload anything from the file system and have no way around, in any browser. To make it work, use a web server, have several alternatives on the web, on Node, Python or using Webmatrix. Then you will be loading from the server itself and will not have this problem.

1 answer

0

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

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 archives server.js and index.html must be in the same folder.

Browser other questions tagged

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