如何使用Javascript和Twig避免多个相同的xhr请求

时间:2018-08-25 21:13:57

标签: javascript symfony twig

我想知道如何避免多个相同的xhr请求以防止加载,以及是否可以建议我这段代码是否安全?

此代码会在页面上加载用户头像。

代码:

{% for bulle in bulles|reverse %}
            {% if bulle.postedBy in app.user.followers %}
                $.ajax({
                    type: "GET",
                    url: "/api/"+"{{ bulle.postedby }}"+"/avatar",
                    dataType: 'json',
                    timeout: 10000,
                    success: function(response) {
                        if (response.avatar == undefined) {
                            $('#img{{ bulle.postedBy ~ loop.index }}').each(function () {
                                $('#img{{ bulle.postedBy ~ loop.index }}').attr('src', 'img/avatar/default.png');
                            });
                        } else {
                            $('#img{{ bulle.postedBy ~ loop.index }}').each(function () {
                                $('#img{{ bulle.postedBy ~ loop.index }}').attr('src', '/uploads/user_avatar/' + response.avatar);
                            });
                        }
                    },
                    error: function() {
                        console.log("API Error, can't get users avatar");
                    }
                });
            {% endif %}
        {% endfor %}

xhr requests screenshot

预先感谢

1 个答案:

答案 0 :(得分:0)

编辑:找到了解决方案symfony.com/doc/3.4/doctrine/associations.html,谢谢@JovanPerovic :)