开发者

jQuery $.each combined with AJAX request - bad practice?

开发者 https://www.devze.com 2023-03-27 09:56 出处:网络
I have this code: $(document).ready(function() { var url = \"https://graph.facebook.com/search?q=cinema&type=post\";

I have this code:

$(document).ready(function() {
            var url = "https://graph.facebook.com/search?q=cinema&type=post";
            $.ajax({
               type: "POST",
               url: url,
               dataType: "jsonp",
               success: function(msg){
                 console.log( msg );
                 $.each( msg.data , function(i,obj){
                    $('#cinemas').append(obj.message + '<br />');

                 });
               }
             });
        });

I can access the message's poster ID like this: data.from.id. What i'd then like to do is run the persons FB ID through an AJAX request and pull back their profile picture.

I imagine i will run another $.each inside an existing $.ea开发者_如何学Goch to run every ID through the AJAX request. So, 1. is this bad practice to have a nested $.each running several AJAX requests and 2. can anyone think of a better way to achieve my scenario?

Thanks


Since you are getting the resultant back in an object and you need something specific to happen with each item, you will need some method of traversing the data. I typically use a standard for loop myself, but that is just out of preference.

The only way to avoid multiple loops would be to get all of the data that you need in one pull, which would then require only one loop.


It is not a bad practice to next $.each or any kind of loops. As a suggestion see if it is possible to send a list of FB IDs in a single request and get the response. This way you dont need the inner $.each loop for each person.

0

精彩评论

暂无评论...
验证码 换一张
取 消