Why does $ .post () not return an object?

1

I have a function something like this:

$('#btn-load-more').click(function(){
    var key = $('#hash').val(), limit = 0, i = 0;
    setTimeout(function(){
        $.post('api', {type: 1, limit: limit, key: 128921}, function(res){
            console.log(res);
        });
    }, 500);
});

The problem is that when you click the button and trigger the event, the result in the console looks exactly like this:

[{"title":"Título de teste","thumb":"2","views":"920134"},{"title":"lorem 
ipsum teste inskl","thumb":"2","views":"920134"}]

When the result should be multiple objects. As in the example below:

(2) [Object, Object]
    ▼ 0: Object
        thumb: "2"
        title: "Título de teste"
        views: "920134"
    ▶ 1: Object

But my goal was to return an object, such as when I change the $.post to $.getJSON , what am I doing wrong?

    
asked by anonymous 30.05.2017 / 02:41

2 answers

4

By default, the $.post function has a fourth parameter that defines the return type. By default, jQuery will try to figure out which type is susceptible to crashes:

$.post(url [, data ] [, success ] [, dataType = "Intelligent Guess" ] );

That is, if unchanged, the return can be any format, such as in your case raw text. Since your return is a JSON, you just need to explicitly change this value to "json" , that your result will arrive as a JavaScript object:

$('#btn-load-more').click(function(){
    var key = $('#hash').val(), limit = 0, i = 0;
    setTimeout(function(){
        $.post('api', {type: 1, limit: limit, key: 128921}, function(res){
            console.log(res);
        }, "json");
    }, 500);
});

According to documentation , this parameter accepts: "xml" , "json" , "script" , "text" and "html" .

    
30.05.2017 / 03:24
1

The appropriate solution is that response, but there is another alternative that is JSON.parse :

var txt = '[{"title":"Título de teste","thumb":"2","views":"920134"},{"title":"lorem ipsum teste inskl","thumb":"2","views":"920134"}]';

var obj = JSON.parse(txt);
console.log(obj);
    
30.05.2017 / 15:29