Why doesn’t $.post() return an object?

Asked

Viewed 98 times

1

I have a function more or less 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);
});

But the problem is that by clicking the button and triggering the event, the result on the console is 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 several 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, as happens when I change the $.post for $.getJSON, what I’m doing wrong?

  • 1

    Set the fourth parameter of $.post as "json". By default, he is string, so its result is not converted to object. Just read the documentation.

  • Thanks man, wow! such an easy problem!

2 answers

4

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

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

That is, if not changed, the return can be any format, as in your case a raw text. Since your return is a JSON, you simply 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);
});

In accordance with the documentation, this parameter accepted: "xml", "json", "script", "text" and "html".

1

The appropriate solution is of that answer, 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);

Browser other questions tagged

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