【问题标题】:Why is this appending multiple times? AJAX为什么这个附加多次? AJAX
【发布时间】:2012-10-17 06:27:48
【问题描述】:

我有这个 ajax 函数。它获取文本区域的值,将其设置为变量,然后将其发送到 instagram。有用。

我想将文本区域值附加到 div 以显示发布的评论,而不刷新页面。它基本上是一个临时可见的评论,当页面重新加载时,它将被 instagram 的实际评论替换。

首先,请忽略我正在尝试做的是在所有这一切的错误字段中。因为我在本地工作,成功不起作用,它被交换了。现在没关系。

我遇到的问题是,当我从文本区域附加数据时,它会附加多次。我目前在我的页面上显示来自 instagram 的 4 张图片。它将在每张照片上附加 4 次文本区域数据,不将数据发送到 istagram,只是附加虚假评论。

如果我从 instagram 中删除 2 张图片,它会为每张图片附加两次...为什么要这样做,我怎样才能做到这一点,当您提交表单时,它会附加一次图片,到那个div。

这是我提交 cmets 的函数。

function instaComment(){

    $('.messageTextarea').keydown(function() {
        if (event.keyCode == 13) {
            this.form.submit();
            return false;
         }
    });

    $('.button').live('click', function(){


        var name = $(this).siblings('.messageTextarea').val();
        var dataString = name;

        $.ajax({
        dataType: 'json',
          url: "https://api.instagram.com/v1/media/"+$(this).attr('data-the_id')+"/comments?"+hash,
          type: "POST",
          data: "text="+dataString,
          success: function(data) {
              // finish load
            console.log(data, dataString, 'succ');
          },
            error: function(data) {
                for (i=0; i < instadata[0].data.length; i++){
                    var username = instadata[0].data[i].user.username;
                    var profilepic = instadata[0].data[i].user.profile_picture;

                    console.log(data, dataString, 'succ');
                    $(this).each(function() {
                        $('.messageComments').append('<li><img class="commentUserImg" src="' + profilepic + '"><div class="commentUser">' + username + '</div><div class="commentText">' + dataString + '</div></li>');
                    });


                }
        }
    });
    return false;
});
}

【问题讨论】:

    标签: ajax append


    【解决方案1】:

    我不确定,但我认为您的问题来自这行代码

      $(this).each(function() {
                            $('.messageComments').append('<li><img class="commentUserImg" src="' + profilepic + '"><div class="commentUser">' + username + '</div><div class="commentText">' + dataString + '</div></li>');
                        });
    

    【讨论】:

    • 我也是这么想的......但我不知道为什么,或者如何解决它。
    猜你喜欢
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多