Ajax and JSON dataType

0

When I do this, return is a parsererror.

$.ajax({
    type: "GET",
    url: "servicos.php",
    data: "id=1",
    dataType: 'json', ==========================> Essa linha bem aqui
    success: function(retorno,status){
    // retorno = JSON.parse(retorno);

    $("#tudo").html(retorno);
},
error: function(retorno,erro){

    $("#tudo").html(retorno.responseText);

}
});

It only gives success if you remove this line or leave it as 'text'.

But (still leaving dataType: 'json'), when I ask to return the error of this fomra:

error: function(retorno,erro){

    $("#tudo").html(retorno.responseText);

}

I get the same success result without the "dataType: 'json'"

I did not understand that.

    
asked by anonymous 03.04.2018 / 18:31

1 answer

1

If you simply copy and paste your ajax request, in theory, it will work. But you should consider the following: I noticed that your servicos.php file returns an array of objects:

  

The return is something like this: [{"id": "1", "name": "juca", "status": "1"}]

So when you "get" the array / array (in success ), you should display the answer like this:

$("#tudo").html(retorno[0].nome);

retorno[0] will reference the first object in the array array returned in the request;

.nome will reference the nome attribute on the returned object;

See the difference in usage:

// Quando o json retornado é array: [{"id":1, "nome":"juca", ...}]
$("#tudo").html(retorno[0].nome);

// Quando o json retornado é objeto: {"id":1, "nome":"juca", ...}
$("#tudo").html(retorno.nome);

Normally, array array is used when it receives more than one object:

json = JSON.parse('[{"id":0,"nome":"jao","status":1},{"id":1,"nome":"juca","status":1},{"id":2,"nome":"ze","status":0}]');

console.log(json[0].nome);  //jao
console.log(json[1].nome);  //juca
console.log(json[2].nome);  //ze

In my tests I used jQuery 1.12.4 .

Upload a project based on this response in my GitHub / LipESprY / sopt-ajax-e-datatype-json

    
25.12.2018 / 00:02