javascript - 为什么 JQuery 不传递替换 div 中的 post_id 和 post_type

标签 javascript jquery django django-templates django-views

我修复了 like/unlike 函数,现在它们可以工作了,但是如果您在单击“Like”后单击“Unlike”(反之亦然)而不重新加载页面,则 post_id 和 post_type 不会传递到 View 。我尝试将它们传递到替换按钮的 html,我可以在新的 div 上看到它们,但也没有从那里传递到 View 。我不知道该怎么办,因为我不明白数据是如何丢失的。我还在替换 html 中放置了两个 div 标签,将 id 和 type 保存为值,因为我需要在替换 html 中使用一个脚本(不知道)才能使按钮正常工作。为什么JS无法从替换的html中抓取数据?

代码相当长,所以我提前道歉

feed.html(主 html 的片段)

                <div class="like-stuff">
                {% if not request.user|user_liked_post:post %}
                <button class='like-post-btn' value="{{like_btn_val}}">
                <span class="glyphicon glyphicon-thumbs-up"></span>
                Like
                </button>                
                {% else %}
                <button class='like-post-btn' value="{{like_btn_val}}">
                <span class="glyphicon glyphicon-thumbs-up"></span>
                Unlike
                </button>
                {% endif %}
                <div class="like-count">{{post.like_count}}<div>

                {% if not request.user|user_disliked_post:post %}
                <button class='dislike-post-btn' value="{{dislike_btn_val}}">
                <span class="glyphicon glyphicon-thumbs-down"></span>
                Dislike
                </button>
                {% else %}
                <button class='dislike-post-btn' value="{{dislike_btn_val}}">
                <span class="glyphicon glyphicon-thumbs-down"></span>
                Undislike
                </button>
                {% endif %}
                <div class="dislike-count">{{post.dislike_count}}</div>
                </div>
<script src="static/js/handle_likes.js"></script>

likes.html(替换html)

<div id="post_id" value="{{post_id}}">id: {{post_id}}</div>
<div id="post_type" value="{{post_type}}">type: {{post_type}}</div>
<div class="like-stuff">

<button class='like-post-btn' value="{{like_btn_val}}">
<span class="glyphicon glyphicon-thumbs-up"></span>
{{like_btn}}
</button>
<h1>{{like_count}}</h1>

<button class='dislike-post-btn' value="{{dislike_btn_val}}">
<span class="glyphicon glyphicon-thumbs-down"></span>
{{dislike_btn}}
</button>
<h1>{{dislike_count}}</h1>
</div>
<script src="static/js/handle_likes.js"></script>

handle_likes.js(类似和不同的函数

$(".like-post-btn").on('click', function(){
    console.log("Thing was clicked!"); // sanity check
    if ($(".like-post-btn").val() == "not-liked") {
        console.log($('.like-post-btn').val());
        like_post();
    }
    if ($(".like-post-btn").val() == "is-liked") {
        unlike_post();
    }

});
// Start functions to handle likes/dislikes
function like_post(){
    console.log("Like post called...") // sanity check
    console.log("Test JQuery like post..");
    console.log($("#post_id"));
    console.log($("#post_type"));
    $.ajax({
        url: "posting/liking_post/",
        data: {
            post_id : $("#post_id").val(),
            post_type : $("#post_type").val()
        },
        success: function(data) {
            console.log(data);
            $('.like-stuff').html(data);
        },
        error : function(xhr,errmsg,err) {
            $('#results').html("<div class='alert-box alert radius' data-alert>Please contact an admin; We have encountered an error: "+errmsg+
                " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
};

function unlike_post(){
    console.log("Unlike post called...") // sanity check
    console.log("Test JQuery unlike post..");
    console.log($("#post_id"));
    console.log($("#post_type"));
    $.ajax({
        url: "posting/unlike_post/",
        data: {
            post_id : $("#post_id").val(),
            post_type : $("#post_type").val()
        },
        success: function(data) {
            $('.like-stuff').html(data);
            },
        error : function(xhr,errmsg,err) {
            $('#results').html("<div class='alert-box alert radius' data-alert>Oops! Please contact an admin for we have encountered an error: "+errmsg+
                " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
};

View .py

@login_required
def like_post(request):
    if request.is_ajax():
        post_id = request.GET.get('post_id')
        post_type = request.GET.get('post_type')
        print("Debug in like_post line 452:",post_id, post_type)
        if not post_id or not post_type:
            raise Exception("Post id or Post type not passed to 'like post' please fix it")
        post = toolz.get_post(post_id, post_type)
        if not user_liked(request.user, post):
            like = Like(
                user=request.user,
                content_object=post
            )
            like.save()
            like_count = post.like_count + 1
            post.like_count = like_count
            print("Like count:", post.like_count)
            post.save()
            # Start data declarations
            like_count = post.like_count
            print(like_count)
            dislike_btn = "Dislike"
            dislike_btn_val = "not-disliked"
            dislike_count = post.dislike_count
            data = {
            'post_id': post_id,
            'post_type': post_type,
            'like_count': like_count,
            'like_btn': 'Unlike',
            'like_btn_val': 'is-liked',
            'dislike_btn':dislike_btn,
            'dislike_btn_val': dislike_btn_val,
            'dislike_count': dislike_count
            }
            return render(None, 'likes.html', data)
        else:
            return HttpResponse("You're trying to like the post twice...stop it")
    else:
        raise Exception("Not ajax")

最佳答案

Div 没有 value 属性(如 valid ),但如果您必须在 div 中使用 value,则可以使用 .attr('value')。

$('#post_id').attr('value')
$('#post_type').attr('value')

关于javascript - 为什么 JQuery 不传递替换 div 中的 post_id 和 post_type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59805233/

相关文章:

javascript - promise 并提交

javascript - GUI 中令人惊叹的聊天机器人查询和回复

javascript - 从另一个页面触发 button.click 事件

jquery - 为选定的下拉选项卡分配值

javascript - 如何在 Canvas 上的图层中绘制图像?

javascript - JavaScript 代码中的三明治模式

javascript - 动态加载的复选框未触发

python - 从 django 模型传递对象的 ID

django.db.utils.OperationalError : cannot ALTER TABLE "forum_thread" because it has pending trigger events

Django Rest Framework POST 和 GET 嵌套序列化程序