-3

I have to make a game, which gives the definition of a word and you have to guess it. It gives me an error while making an Ajax request:

jquery-3.2.1.js:9566 Access to XMLHttpRequest at 'file:///D:/Grado%20Superior/2do/DWEC/logogrifo_CristinaBorrego/logogrifo.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
send @ jquery-3.2.1.js:9566
ajax @ jquery-3.2.1.js:9173
jQuery.(anonymous function) @ jquery-3.2.1.js:9322
getJSON @ jquery-3.2.1.js:9303
(anonymous) @ index.html:44
jquery-3.2.1.js:3860 jQuery.Deferred exception: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefined
    at HTMLDocument.<anonymous> (file:///D:/Grado%20Superior/2do/DWEC/logogrifo_CristinaBorrego/index.html:55:62)
    at mightThrow (https://code.jquery.com/jquery-3.2.1.js:3583:29)
    at process (https://code.jquery.com/jquery-3.2.1.js:3651:12) undefined
jQuery.Deferred.exceptionHook @ jquery-3.2.1.js:3860
process @ jquery-3.2.1.js:3655
setTimeout (async)
(anonymous) @ jquery-3.2.1.js:3689
fire @ jquery-3.2.1.js:3317
fireWith @ jquery-3.2.1.js:3447
fire @ jquery-3.2.1.js:3455
fire @ jquery-3.2.1.js:3317
fireWith @ jquery-3.2.1.js:3447
ready @ jquery-3.2.1.js:3920
completed @ jquery-3.2.1.js:3930
jquery-3.2.1.js:3869 Uncaught TypeError: Cannot read property 'length' of undefined
    at HTMLDocument.<anonymous> (index.html:55)
    at mightThrow (jquery-3.2.1.js:3583)
    at process (jquery-3.2.1.js:3651)

My code:

<!doctype html>
<html lang="es">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
    <!-- <link rel="stylesheet" href="estiloCargando.css"> -->
    <title>Logogrifo</title>
  </head>
  <body>
    <div class="container">
      <h1>Logogrifo</h1>
      <div class="row">
        <div class="col-md-8 offset-md-2">
          <div id="res">
            <div class="loader"></div>
          </div>
        </div>
      </div>

    </div>
    <script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js" integrity="sha384-a5N7Y/aK3qNeh15eJKGWxsqtnX/wWdSZSKp+81YjTmS15nvnvxKHuzaWwXHDli+4" crossorigin="anonymous"></script>
        <script>
            var showData = $('#res');
            var arrayPalabras = [];
            var arrayPistas = [];
            var letrasPalabras = [];
            var numeros = 0;
            var letrasPalabrasUnique;
            var html = "";
            // Prototype para eliminar elementos repetidos en un array.
            Array.prototype.unique = function() {
              return this.filter(function (value, index, self) {
              return self.indexOf(value) === index;
              });
            }
            // Obtención de palabras y pistas.
            $.getJSON('logogrifo.json', function(data){
              $.each(data, function(key, val){
                arrayPalabras.push(data[key].palabra);
                arrayPistas.push(data[key].definicion);
              });
            });
          $(document).ready(function(){
            var randomIndex = Math.floor((Math.random() * arrayPalabras.length));
            var arrayPalabrasSort = [];
            for (var i = 0; i < 7; i++) {
              html += "<div class='divPalabra'>";
              for (var e = 0; e < arrayPalabras[randomIndex].length; e++) {
                html += "<input type='text' size='1' maxlength='1'/>";
                letrasPalabras.push(arrayPalabras[randomIndex][e]);
              }
              html += "</div>";
              arrayPalabras.splice(randomIndex, 1);
              html += "<p>"+arrayPistas[randomIndex]+"</p>";
              arrayPistas.splice(randomIndex, 1);
              randomIndex = Math.floor((Math.random() * arrayPalabras.length));
              // arrayPalabras.sort(function(a, b) {
              //   return a.length - b.length;
              // }).reverse();
            }
            showData.append(html);
            html = "";
            letrasPalabrasUnique = letrasPalabras.unique();
            $("input").each(function(a){
                $(this).attr("name",letrasPalabras[a]);
              });
            $(".divPalabra").each(function(z){
              $(this).children().each(function(){
                for (var i = 0; i < letrasPalabrasUnique.length; i++) {
                  if ($(this).attr('name') == letrasPalabrasUnique[i]){
                    if (i >= 9) {
                      html += "<span class='m'>" + (i+1) + "</span>";
                    } else html += "<span>" + (i+1) + "</span>";
                  }
                }
              });
              $(this).before(html);
              html = "";
            });
            $("input").on('change',function(){
              //alert($(this).val());
              if ($(this).val() != "") {
              var letraJugador = $(this).val().toUpperCase();
              if ($(this).attr('name') == letraJugador) {
                $("input[name='"+letraJugador+"']").val(letraJugador);
                $("input[name='"+letraJugador+"']").attr('disabled','disabled');
                if ($(":disabled").length == letrasPalabras.length) {
                  alert("juego finalizado");
                }
                //alert($(":disabled").length);
              }
              else {
                $(this).val("");
              }
            }
              });
          });
        </script>
  </body>
</html>
ttulka
  • 10,309
  • 7
  • 41
  • 52
  • Your code throws an error: "Uncaught TypeError: Cannot read property 'length' of undefined". That means that somewhere you wrote `.length` but the thing before returned undefined. Try using `console.log` to print those values before the .length`, until one prints `undefined` – Federico Grandi Mar 02 '19 at 17:57
  • As a rule of thumb, when you get an error message you don't understand, you can usually find an explanation for it by copy/pasting it into Google before you resort to StackOverflow. – Quentin Mar 03 '19 at 11:28

1 Answers1

-2

As it requires Cors enable So that you can make a request to fetch the data and as you have not enable the cors on your side so it's not providing you the data. Fix that first and ".length" will not work with null or undefined data.

Cross origin requests are only supported for protocol

Shailesh Jha
  • 1,122
  • 1
  • 8
  • 9
  • They **can't** "enable CORS", the error message you quoted says that CORS is not supported for the protocol they are using. – Quentin Mar 03 '19 at 11:27