I can’t "read" a JSON

Asked

Viewed 534 times

0

I am working on the FLUIG (TOTVS) tool, and I want to read a JSON that is delivered via REST. Here is a photo of the URL (intranet):

inserir a descrição da imagem aqui

Contents:

{"content":{"Matrícula_RH":"10555","UserDocLanguage":"pt_BR","UserEmailHTML":"true","UserProjects":"","UserQuotaDocument":"500","UserSpecialization":"","UserWorkflowGroup":"TI","UX-APP-COMPANY":"88303375000171_0240050312_RS","WCMUserLang":"pt_BR"},"message":{"message":"OK","detail":"OK","type":"INFO","errorCode":null}}

JSON reading code:

function executa() {
    var url = "http://10.0.0.1:8181/api/public/2.0/users/listData/teste";
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            var json = JSON.parse(xmlhttp.responseText);
            var contador = json.length;
            alert(contador);
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

but always gives this error in the browser console(Chrome):

Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.xmlhttp.onreadystatechange (rest.html:17)

When I look, the wrong line is this:

var json = JSON.parse(xmlhttp.responseText);

Am I treating JSON wrong? I took this code from the internet and found it very generic, researched about this error and tested some changes without success. I am very beginner in javascript, if someone can explain to me why this does not work and which is the correct method I appreciate.

I tried a new code that worked just need to learn how to get the JSON content:

function executa_new() {
    $.ajax({
        type: 'GET',
        url: 'http://10.0.0.1:8181/api/public/2.0/users/listData/teste',
        dataType: 'jsonp',
        success: function() {    
            console.info("foi");
        }, error: function(e){
             alert('Ocorreu um erro durante a chamada ' + e);
        }
    });
}
  • 3

    Gives a console.log(xmlhttp.responseText) to see what’s in the output. with F12 -> console you can check the output. Something else, try JSON.parse(xmlhttp.responseText.content)

  • It brings a completely different HTML page: https://pastebin.com/LQkCFtKz

  • see the file you call by ajax, the problem may be in it q is calling something that returns information before the time.

1 answer

0


Solved:

function executa_new() {
    $.ajax({
        type: 'GET',
        url: 'http://10.0.0.1:8181/api/public/2.0/users/listData/teste',
        dataType: 'jsonp',
        success: function (data) {
            console.info(data);
            console.info(data.content);
            console.info(data.content["Matrícula_RH"]);

        }, error: function(e){
             alert('Ocorreu um erro durante a chamada ' + e);
        }
    });
}

Thanks for the help!

Browser other questions tagged

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