Error consuming json using ajax

Asked

Viewed 1,246 times

1

I have the following return in json:

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

Of webservice done in WCF I am using the following code:

<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>
<script type="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', I saw that json is invalid, like "convert" to a valid json?

Error occurs on line var myData = JSON.parse(result.d), follow the full error message:

(index):1 Uncaught Syntaxerror: Unexpected token u in JSON at position 0 at JSON.parse () At Object.Success ((index):31) 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)

the return of the variable result:

Object {Query Texttexttextsummary: Object}

  • In which line does the error occur? in Rows?

  • Put what’s coming in the variable result to help you better...

  • I edited and added what you suggested, obg

  • @Intelidersistemas The json return you have placed is from result or result.d? If it’s from result take off the .d of JSON.parse.

  • if I take . d the error changes Uncaught SyntaxError: Unexpected token o in JSON at position 1, error happens on the same line

  • I would like to see obj: result, q already seems to be coming deserialized.

  • var myData = JSON.parse(result. d); to: var myData = JSON.parse(result);

  • @Aline change to what you indicated the error changes: Unexpected token o in JSON at position 1

Show 3 more comments

1 answer

2


Your JSON return seems to be correct, what it does not seem is 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

  1. No need to use JSON.parse to get the result. You already specified for jQuery that your return will be a JSON on dataType: "json" and in this way the jQuery already delivers to you in result a Javascript object built from JSON. In this case you would be trying to do the parse of an object, not a string, generating the error. This .d it doesn’t make any sense to be there either;

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

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

  • really missed attention in some points, I made the changes I understood but still continues the error and was like this: var table = $("#datagrid"); var Rows = ""; table.find("tbody td"). remove(); for (var i = 0; i < result.length; i++) { var obj = result[i]; Alert(obj.Login); it is saying that the object is undefined from the result. Local i : 0 obj : Undefined result : Object Query;proto : Object Rows : ""

  • 1

    Anderson the above code worked only by modifying how I get the result value, e.g.: result.ConsultarRegistroPorCodigoResult.Codig, and it worked blz, thanks for the help and attention!

  • After making the changes suggested by you!

Browser other questions tagged

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