javascript - 如何将html循环中的模板变量发送到javascript?

标签 javascript html django django-templates

我在 html 中有一个模型的 Post 类变量,我想添加向任何帖子添加评论的功能。所以我有一个js函数,用于单击按钮添加评论,我想发送那个用户想要为其添加评论的post_id,但由于这个标签处于循环中,它总是发送相同的post_id! 我能做什么??

html:

{% extends "base.html" %}
   {% block body_block %}
       <h2>Profile:</h2>
       <h2>Posts:</h2>
       {% for temp_user_posts in user_posts %}
           <div class="profile_page">
               <h3><b>{{ temp_user_posts.post }}</b></h3>
               <p>{{ temp_user_posts.post_time }}</p>

           </div>
               <label for="user-comment">comment:</label>
               <input id="user-comment" type="text" name="{{ temp_user_posts.pk 
   }}">
               <button onclick="add_comment_button();">add comment</button>

       {% endfor %}

   {% endblock %}

js:

function add_comment_button() {
    alert($('#user-comment').attr("name"));
    $.ajax({
        type: "GET",
        url: '/user_add_comment',
        data: {
            "comment_text": $('#user-comment').val(),
            "post_pk": $('#user-comment').attr("name"),
        },
        dataType: "json",
        success: function (data) {
            location.href = data["url"]
        },
        failure: function () {
            alert('There is a problem!!!');
        }
    });
}

查看:

def user_add_comment(request):
    post_pk = request.GET.get('post_pk', None)
    post = PostModel.objects.get(pk=post_pk)
    comment = CommentPostModel()
    comment.post = post
    user_info = UserProfileInfo.objects.filter(user=request.user)
    user_info2 = object()
    for temp_user_info in user_info:
        user_info2 = temp_user_info
        break
    comment.profile_user = user_info2
    comment.text = request.GET.get('post_text', None)
    comment.save()
    data = {
        "url":"/profile_page",
    }
    return JsonResponse(data)

型号:

class UserProfileInfo(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=100, blank=True, default="Bio")
    profile_pic = models.ImageField(upload_to='profile_users', blank=True)

    def __str__(self):
        return self.user.username


class PostModel(models.Model):
    username = models.CharField(max_length=20, unique=False, verbose_name="Username", default="")
    image = models.ImageField(upload_to='user_images', blank=True)
    post = models.TextField(max_length=100, blank=True)
    post_time = models.DateTimeField(default=datetime.now, blank=True)

    def set_post_time(self):
        self.post_time = datetime.now()
        self.save()

    def __str__(self):
        return self.username

最佳答案

尝试将帖子 pk 放入输入 id 中并作为按钮函数参数:

<input id="user-comment-{{ temp_user_posts.pk }}" type="text" name="{{ temp_user_posts.pk }}">
<button onclick="add_comment_button({{ temp_user_posts.pk }});">add 
comment</button>

然后您就可以发送 GET 请求中的具体内容了:

function add_comment_button(postPk) {
$.ajax({
    type: "GET",
    url: '/user_add_comment',
    data: {
        "comment_text": $('#user-comment-' + postPk).val(),
        "post_pk": postPk,
    },
    dataType: "json",
    success: function (data) {
        location.href = data["url"]
    },
    failure: function () {
        alert('There is a problem!!!');
    }
});
}

关于javascript - 如何将html循环中的模板变量发送到javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54774378/

相关文章:

javascript - 如何检查名为 id 的变量属性?

javascript - 将处理程序附加到动态创建的元素..

python - Django:如何为登录用户数据的查询集编写 Mixin

django - 如何在模型上使用 OrderingFilter 和其他 Filterset 过滤

javascript - 通过 javascript 显示上传百分比,就像 chrome 的左下角一样

javascript - 如何在javascript中暂停递归函数3秒?

javascript - Push.apply() 不增加数组大小

html - 如何仅使用 css 在 Div 中切换效果?

html - 盒子大小,为什么高度 > 100%?

django - 访问 django 中的模型字段和属性