Error consuming json using ajax

1

I have the following return in json:

{
    "ConsultarRegistroPorCodigoResult": {
        "Codigo": 2,
        "CodigoSetor": 1,
        "Login": "ednilson1",
        "Nome": "Ednilson",
        "RegistroAtivo": true,
        "Senha": "123456",
        "Tipo": "D"
    }
}

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form id="form1">
    <div class="jumbotron">
        <input type="text" id="codUser"/>
        <button onclick="ConsUsuario(); return false;">Consulta Usuario</button>
    </div>

      <div><table id="datagrid"></table></div>
</form>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script><scripttype="text/javascript">
    function ConsUsuario(){
        var value = $("#codUser").val();

        $.ajax({
        type: "GET",
        url: "ServiceRestPub/ServiceUsuario.svc/ConsultarRegistroPorCodigo/" + value,
        contentType: "application/json",
        dataType: "json",
        success: function (result) {
          debugger;
          var tabela = $("#datagrid");
                            var rows = "";
                            tabela.find("tbody td").remove();

                            var myData = JSON.parse(result.d);
                            for (var i = 0; i < myData.length; i++) {
                                var obj = myData[i];
                                alert(obj.descricao);


                                rows += "<tr>";
                                rows += " <td>" + obj.id_usuario + "</td>";
                                rows += " <td>" + obj.nm_usuario + "</td>";
                                rows += " <td>" + obj.ds_login + "</td>";
                                rows += " <td> <input type='checkbox' /> </td>";
                                rows += "</tr>";
                            }

                            // tabela.find("tbody").html(rows);
                tabela.html('<tbody>' + rows + '</tbody>');

            //console.info(result.d);
            }
        });
    }
 </script>

Returns the error 'Unexpected token u in JSON at position 0' , so I saw json as invalid, as "convert" to a valid json?

The error occurs at line var myData = JSON.parse(result.d) , the complete error message follows:

  

(index): 1 Uncaught SyntaxError: Unexpected token in JSON at   position 0       at JSON.parse ()       at Object.success ((index): 31)       at l (jquery.min.js: 2)       at Object.fireWith [as resolveWith] (jquery.min.js: 2)       at T (jquery.min.js: 2)       at XMLHttpRequest.r (jquery.min.js: 2)

return of variable result :

  

Object {CheckRegistrationCodeResult: Object}

    
asked by anonymous 10.05.2017 / 12:45

1 answer

1

Your JSON return seems to be correct, which does not seem to be the way you treat it.

$.ajax({
  type: "GET",
  url: "ServiceRestPub/ServiceUsuario.svc/ConsultarRegistroPorCodigo/" + value,
  contentType: "application/json",
  dataType: "json",
  success: function(result) {
    debugger;
    var tabela = $("#datagrid");
    var rows = "";
    tabela.find("tbody td").remove();

    var myData = JSON.parse(result.d); // <~~~~~~~~~~~~~~~~~~~~ (1)
    for (var i = 0; i < myData.length; i++) { // <~~~~~~~~~~~~~ (2)
      var obj = myData[i];
      alert(obj.descricao); // <~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (3)


      rows += "<tr>";
      rows += " <td>" + obj.id_usuario + "</td>"; // <~~~~~~~~~ (3)
      rows += " <td>" + obj.nm_usuario + "</td>"; // <~~~~~~~~~ (3)
      rows += " <td>" + obj.ds_login + "</td>"; // <~~~~~~~~~~~ (3)
      rows += " <td> <input type='checkbox' /> </td>";
      rows += "</tr>";
    }

    // tabela.find("tbody").html(rows);
    tabela.html('<tbody>' + rows + '</tbody>');

    //console.info(result.d);
  }
});

Explanations

  • No need to use JSON.parse to get the result. You have already specified for jQuery that your return will be a JSON in dataType: "json" , and thus jQuery will already deliver to you as a% of a JavaScript object built from JSON. In this case you would be trying to parse an object, not a string , generating the error. This result also makes no sense to be there;

  • In your case, .d will be a JavaScript object with only one attribute. result , which will also be an object. At this point in the code you seem to want to iterate over ConsultarRegistroPorCodigoResult as if it were a list of objects. It would not produce any syntactic error, but the result would not be expected, because instead of being iterating over a list of objects, you would be iterating over the object itself;

  • At these points you try to access object attributes that are not defined in your JSON. Note that the object defined in result has only the attributes result.ConsultarRegistroPorCodigoResult , Codigo , CodigoSetor , Login , Nome , RegistroAtivo , Senha and 123456 . You try to use Tipo , descricao , id_usuario and nm_usuario . None of them exist on your return.

  • 10.05.2017 / 14:25