Chelseawillrecover
Chelseawillrecover

Reputation: 2644

JSON object looped multiple times

Hi I seem to have gotten myself stuck with the data passed by JSON. When I console log to see the data passed, the object are repeatedly passed and this is affecting my append output.

$.ajax({
            url: "http://howtodeployit.com/api/get_recent_posts",
            dataType: "json",
            jsonpCallback: 'successCallback',
            async: true,
            beforeSend: function() { $.mobile.showPageLoadingMsg(true); },
            complete: function() { $.mobile.hidePageLoadingMsg(); },
            success:function (data){
                $.each(data.posts, function(key, val) {
                console.log(data.posts);

                var result = $('<li/>').append([$("<h3>", {html: val.title}),$("<p>", {html: val.excerpt})]).wrapInner('<a href="#devotionpost" onclick="showPost(' + val.id + ')"></a>');

                $('#postlist').empty().append(result);
            });

As seen below, this is appearing multiple times but the expected output should just be one line of object. enter image description here

Upvotes: 0

Views: 485

Answers (2)

loxxy
loxxy

Reputation: 13151

If you are trying to load jsonp, the dataType should be jsonp

Also I do think you are trying to loop over each post. But there would be only one result since you empty the container every time.

So instead of :

$('#postlist').empty().append(result);

Use

$('#postlist').append(result);

And did you miss a closing braces??

$.ajax({
    url: "http://howtodeployit.com/api/get_recent_posts",
    dataType: "jsonp",
    jsonpCallback: 'successCallback',
    async: true,
    beforeSend: function () {
        // $.mobile.showPageLoadingMsg(true);
    },
    complete: function () {
        //  $.mobile.hidePageLoadingMsg();
    },
    success: function (data) {
        $.each(data.posts, function (key, val) {
            console.log(data.posts);

            var result = $('<li/>').append([$("<h3>", {
                html: val.title
            }), $("<p>", {
                html: val.excerpt
            })]).wrapInner('<a href="#devotionpost" onclick="showPost(' + val.id + ')"></a>');

            $('#postlist').append(result);

        });
    }
});

here is a DEMO.

Upvotes: 0

Yevgeny Simkin
Yevgeny Simkin

Reputation: 28369

$.each(data.posts, function(key, val) {

That is a loop. So, assuming that the data.posts is an array that has multiple objects, you will see this fired as many times as there are posts.

What are you hoping to see?

Also, loxxy is right, you're missing a closing brace so it's hard to know where you intend your loop function to actually end.

Upvotes: 1

Related Questions